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

128
Views
dynamic Button class does not update after the array change

So I have an array of objects. I iterate through this array and create a button for each object. When a button is pressed that object of the button pressed has a value "active" that will be set to true. when another button is pressed its "active" value is now true all all the other ones are turned to false.

it looks like this

myarray.map(item =>
        <Button
          className={item.active? "btn-active" : "btn-disabled"}
          onClick={() => setActive(item);
          }}
        >
          {item.active? "Checking..." : "Start"}
        </Button>
)

The behavior I expect is when a button is pressed it turns to action, and all the rest remain inactive, when a new button is pressed the new button is now active and all the rest are disabled. only one active button at a time.

However, the issue I am having is when a new button is pressed it turns to active, but the old one does not change class and stays active also even though it "active" property is set to false.

Any idea how can I fix this behavior?

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

0

Without a full picture of how you are using state, here is a working example. Another issue I seen is that you are missing a key on your mapped jsx element.

It's possible you are not mutating myarray statefully.

import "./styles.css";
import React from "react";

export default function App() {
  const [myarray, setMyarray] = React.useState([
    { id: 1, active: false },
    { id: 2, active: false }
  ]);

  const setActive = (id) => {
    setMyarray((prev) =>
      prev.map((item) => {
        if (item.id === id) {
          return { ...item, active: true };
        }
        return { ...item, active: false };
      })
    );
  };

  return (
    <div className="App">
      {myarray.map((item) => (
        <button
          key={`button-${item.id}`}
          className={item.active ? "btn-active" : "btn-disabled"}
          onClick={() => setActive(item.id)}
        >
          {item.active ? "Checking..." : "Start"}
        </button>
      ))}
    </div>
  );
}

https://codesandbox.io/s/flamboyant-shirley-i24v0z

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!