Search code examples
javascriptreactjsbootstrap-4react-hooksreact-bootstrap

onClick Event Using react-bootstrap nav dropdown and react-router-dom not working


I have the following Navbar using react-bootstrap. The second brand is always the one that is active, as if the dropdown is consistently clicked on the last item in the chain (in this case Tommy Hilfiger). I need to have the brand set based on which item in the dropdown is clicked.

const [brand, setBrand] = useState("");

 const brandSet = (value) => {
    setBrand(value);
  };

<Navbar bg="light" expand="lg">
          
              <NavDropdown title="Brands" id="basic-nav-dropdown">
                <NavDropdown.Item href="/#/products">
                  All Products
                </NavDropdown.Item>
                <NavDropdown.Item
                  href="/#/products:PoloRalphLauren"
                  onClick={brandSet("Polo Ralph Lauren")}
                >
                  Polo Ralph Lauren
                </NavDropdown.Item>
                <NavDropdown.Item
                  href="/#/products:TommyHilfiger"
                  onClick={brandSet("Tommy Hilfiger")}
                >
                  Tommy Hilfiger
                </NavDropdown.Item>

Solution

  • Because you are calling that function instead of passing the function to onClick, change that line to this:

            <NavDropdown.Item
                 href="/#/products:PoloRalphLauren"
                 onClick={() => brandSet("Polo Ralph Lauren")}
             >
                Polo Ralph Lauren
            </NavDropdown.Item>
    

    => called Arrow Function, which was introduced in ES6, and will be supported on React 0.13.3 or upper.