Introduction
When creating a filter function in React, I was a little confused by the argument syntax for toggleOptions("optionA")}>, so I've organized it for clarity.
Problem
I originally wrote it like this:
const [options, setOptions] = useState({ A: false, B: false });
const toggle = (key) => {
setOptions(prev => ({ ...prev, [key]: !prev[key] }));
};
<button onClick={toggle}>A</button>
The reason it doesn't work when clicked is because the key isn't passed.
Solution
Write it so that "A" is passed when clicked.
<button onClick={() => toggle("A")}>A</button>
<button onClick={() => toggle("B")}>B</button>
This passes "A" and "B", which toggle between true and false, respectively.
Summary
I'd like to summarize the basics once again.
Top comments (0)