Skip to content
Advertisement

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?

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement