Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

243
Views
ReactJS onclick toggle class event multiple times

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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"/>
    </>
  );
}
about 4 years ago · Juan Pablo Isaza Report

0

This is for reference:

Edited answer from Magofoco

Passing button text & ID:

const MyButtonComponent = ({ myText, myId }) => {
  const [isActive, setActive] = React.useState(false);

  return (
    <Button
      onClick={() => setActive(!isActive)}
      className={`toggle ${isActive ? "active" : ""}`}
      id={myId}
    >
      {myText}
    </Button>
  );
};

export default function App() {
  return (
    <MyButtonComponent myText="something" myId="tab01" />
  );
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!