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

120
Views
React toggle boolean working on all elements instead of just one

My react hooks are toggling all elements instead of just the single element. And, I don't know why ?

Expected behavior = select a button, classname changes, calls the function click the same button, classname changes and calls the function.

Instead, whatever I select causes every other element to be selected. And, if i select a different button, it removes whatever was stored in localstorage.

The hook

const [color, setColor] = useState(false)

function addOrRemove(e) {
  const elem = e.currentTarget;
  setColor(!color)
if (color){
  addValue(elem)
} else {
  removeValue(elem)
}
}

function addValue(e) {
    if (e.value !== "") {
      
      if (!favs.includes(e.value)) {
        favs.push(e.value);
        localStorage.setItem("name", JSON.stringify(favs));
        console.log(favs);
        document.getElementById("favsarray").innerHTML =  favs
      }
    }
  }

function removeValue(e, value) {
    if (e.value !== "") {
      //delete from array
      favs.pop(e.value);
      console.log(favs);
      //change the div text
      document.getElementById("favsarray").innerHTML = favs;
      //get the values from localstorage- parse
      const stored = JSON.parse(localStorage.getItem("name"));
      //delete the value
      delete stored[(value, e.value)];
      //store the new array as a string
      localStorage.setItem("name", JSON.stringify(favs));
      console.log(stored);
    }
  }

calling this function

<button
                id="btn"
                onClick={addOrRemove}
                className={color? "red": "white"}
                value={"Name:  " + d.name + "  Description:   " + d.description + "  Stars:   " + d.stargazers_count + "  URL:   " + d.html_url}
            
about 4 years ago · Juan Pablo Isaza
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!