Issue
How can I use this onclick toggle class event multiple times?
const [isActive, setActive] = React.useState(false);
<button
onClick={() => setActive(!isActive)}
className={`toggle ${isActive ? "active" : ""}`}
>
Categories
</button>
Here is the issue in Sandbox: https://codesandbox.io/s/agitated-pond-tewk9h?file=/src/App.js
When click on any button it works for all others.
Solution
You should create a component for your button that contains the useState. Else, the useState is global for all the components that use it.
Example: https://codesandbox.io/s/withered-feather-vj8owx?file=/src/App.js
const MyButtonComponent = ({myText}) => {
const [isActive, setActive] = React.useState(false);
return (
<button
onClick={() => setActive(!isActive)}
className={`toggle ${isActive ? "active" : ""}`}
>
{myText}
</button>
);
};
export default function App() {
return (
<>
<MyButtonComponent myText="Something" />
<MyButtonComponent myText="Something else"/>
<MyButtonComponent myText="Else something"/>
</>
);
}
Answered By - Magofoco
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.