Now that we've moved the Home component from the top level of the component tree, our addToCart
setter and state will no longer be in the scope of the top App component as the Home component is now rendering the products further down the tree.
This is now an issue because we will want to display the number of items in the cart in the header section at the top level of the app, at present it is trapped inside the Home component and when we navigate to About or Contact we lose the ability to access and reference the number of items in the cart.
We want the cart state to be global for our app so it needs to be in the highest level component (the App component). We need to move the cart state up from the Home component and pass the props down to Home and Product. This is a common framework pattern in React to share state between many components.
Let move the [cart, setCart] and addToCart variables and functions out of Home and into App. Now pass down the addToCart function from App to Home to Product. When you are passing addToCart down to the Product component you will now have to reference it using props.addToCart like this:
<Product key={product.productId} product={product} addToCart={props.addToCart} />
Now in the App component we have some navigation already, let us build that out to include the brand header for the site, and the cart. You can add some css to make this look right. My Header now looks some thing like this:
<header>
<h1>Plants Direct</h1>
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/contact">Contact</Link>
</nav>
<section>🛒 ({cart.length})</section>
</header>
Our refactor now means we have the cart state being rendered in the header and it remains as we navigate from page to page.
props.data.products
.