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

305
Views
How to target DOM and change style in react with mapped elements

I have a multi page form that renders a list of buttons for each possible answer.

I am currently using getElementByID to change the button style when a button is clicked. I think this is not considered good practice in react.

can I use the useRef hook to target the DOM element and change its style instead of using getElementByID if the buttons are dynamically displayed with map?

{answers.map((answer, count = 0) => {
        return (
          <Button
            key={count}
            id=`button${count}`
            onClick={(e) => {        
              document.getElementById(`${e.currentTarget.id}`).style.color = "white";
            }}
          >
            <ButtonTitle>{answer.name}</ButtonTitle>
          </Button>
        );
      })}

(animations on safari are breaking the active style, so I can't use the active pseudo element)

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

0

You can do this by adding a new state and toggle active class by that state. Code something like this.

const [activeindex, setActiveIndex] = useState("");

return(
<>
{answers.map((answer, count = 0) => {
        return (
          <Button
            key={count}
            className={count==activeindex?"acvie":""}
            onClick={(e) => {        
              setActiveIndex(count)
            }}
          >
            <ButtonTitle>{answer.name}</ButtonTitle>
          </Button>
        );
      })}
}
</>

And use .active class in css file.

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!