I need the Cart component in Navbar.js to open whenever i click on the "Add To Cart" button in the CartButton component which is found in multiple pages.
here is the code and what i tried so far but it doesn’t work:
Navbar.js
const Navbar = () => {
const [open, setOpen] = useState(false);
const toggleCart = () => {
setOpen(!open);
};
return (
<header>
<div>
<nav>
<ul>
<li>
<HiOutlineShoppingBag onClick={() => toggleCart(open)} /> ----> function to have the cart component open when i click on the shopping bag icon (this works perfectly)
</li>
</ul>
</nav>
</div>
{open && <Cart />} --------> Opens the cart component.
</header>
);
};
export default Navbar;
CartButton.js
const CartButton = ({ open, setOpen }) => {
return (
<button onClick={() => setOpen(open)} ----> need this to open the <Cart /> component in Navbar.js
<HiOutlineShoppingBag />
<p className="text-bold">Add To Cart</p>
</button>
);
};
export default CartButton;
i get the error "setOpen" is not a function.. how do i fix it?
2
Answers
pls, show the place you call CartButton component and check if you sending it the props, you try to use (open, setOpen)
should be smth like this
also I can’t understand, you try to export Navbar as default, but show the HeaderComponent, it wouldn’t work I guess.
The
<HiOutlineShoppingBag />
is also a component, correct?You need to pass
setOpen
state as props into itAnd then inside the
HiOutlineShoppingBag
component you run the functionthis way you will be able to change the state value in the NavBar component.
But if your project is big or you need a more solid solution, I advise you to use React’s
useContext
hook. It can make the variables and functions created within it available globally in your projecthttps://legacy.reactjs.org/docs/hooks-reference.html#usecontext