Reputation: 6991
I have created a simple dropdown menu using React hooks. It works as I want it to with one exception -- it opens up all dropdown menus at once. This makes sense given that I'm using a single state that I use for all dropdown instances:
const [open, setOpen] = useState(false)
I then use onClick (and onBlur) to set the state whenever someone clicks on a dropdown menu:
onClick={() => setOpen(state => !state)}
onBlur={() => setOpen(false)}
When open
is set to true
, the dropdown menu is set to display: block;
. When it is false, it is set to display: none;
This is set in the css (using Styled Components).
So this all works fine for a single dropdown menu -- the problem is, every instance of the dropdown menu is connected to the state of open
. That means that if open is set to true, then every dropdown menu displays - false, none of them display.
How can I modify the dropdown menu so that I can toggle only the dropdown menu that is being clicked on?
Thanks.
Upvotes: 0
Views: 2054
Reputation: 116
If you are going to use your Dropdown more than once, then what you should do is to make it as a component so each one controls it's own state.
const Dropdown =() => {
const [open, setOpen] = useState(false);
onClick=() => setOpen(state => !state)
onBlur=() => setOpen(false)
return (<input onClick={this.onClick}>
....
</input>)
}
const otherComponent = () => {
return (
<div>
<Dropdown/>
<Dropdown/>
</div>
)
}
Upvotes: 7