Show one dropdown on hover with hooks

Viewed 123

I want to use react hooks to show some dropdowns when hovering on them. Came up with this:

const [show, setShow] = useState(false);
    const showDropdown = (e) => {
        setShow(!show);
    };
    const hideDropdown = (e) => {
        setShow(false);
    };

Here's a dropdown sample:

   <NavDropdown
   title="Tales"
   id="basic-nav-dropdown"
   show={show}
   onMouseEnter={showDropdown}
   onMouseLeave={hideDropdown}>
      <NavDropdown.Item>...</NavDropdown.Item>
   </NavDropdown>

When I ran it and tested it, I noticed that every time I was hovering on one of the dropdowns, every dropdown was opening. Is there a way to do what I said before without doing a hook for every dropdown?

1 Answers

That is because you're using the same state for every dropdown. One solution would be to give a unique id to each dropdown and then compare the unique id to the state and see if that is the dropdown that should be open:

const [activeDropdown, setActiveDropdown] = useState('');
    const showDropdown = (title) => {
        setActiveDropdown(title);
    };
    const hideDropdown = () => {
        setActiveDropdown('');
    };

<NavDropdown
   title="Tales"
   id="basic-nav-dropdown"
   show={activeDropdown === 'Tales'} << --- Compare if this is the active dropdown
   onMouseEnter={() => showDropdown('Tales')} <<-- Pass the title to the state
   onMouseLeave={hideDropdown}>
      <NavDropdown.Item>...</NavDropdown.Item>
   </NavDropdown>
Related