skip to Main Content

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


  1. 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

    <CartButton open={open} setOpen={setOpen} />
    

    also I can’t understand, you try to export Navbar as default, but show the HeaderComponent, it wouldn’t work I guess.

    Login or Signup to reply.
  2. The <HiOutlineShoppingBag /> is also a component, correct?

    You need to pass setOpen state as props into it

    <header>
      <div>
        <nav>
          <ul>
            <li>
                <HiOutlineShoppingBag setOpen={setOpen}/>
            </li>
          </ul>
        </nav>
      </div>
      {open && <Cart />} --------> Opens the cart component.
    </header>
    

    And then inside the HiOutlineShoppingBag component you run the function

    export function HiOutlineShoppingBag({ setOpen }) {
      return (
       <button onClick={() => setOpen(true)}>
        submit 
       </button>
     )}
    

    this 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 project

    https://legacy.reactjs.org/docs/hooks-reference.html#usecontext

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search