Noble Polygon
Noble Polygon

Reputation: 806

Toggle Single Item in array of data

I'm working with mapped data in React which renders a row of information. In this row, I have the option to update the data based on the toggle state.

I have a default boolean value useState(true) which shows the initial button value.

However, in my component, when I call click this button, the values for all listed items are changed. My example is here in this link:

https://stackblitz.com/edit/react-nzssbv

How do I change the value for just that specific row? I've seen some examples here on SO which use useState(0) or creating a constant with a preset number of buttons.

EXAMPLE:


const btnState = {
  normal: 0,
  btn1Clicked: 1,
  btn2Clicked: 2,
}

However, since the size of the array can change with more or less data, what is the best way to handle this toggle? I would think by the id of the specified data, but I'm not sure.

Upvotes: 0

Views: 316

Answers (1)

blankart
blankart

Reputation: 716

Move the const [toggleImpact, setToggleImpact] = useState(true) in your memoized component Row

  const Row = React.memo(function Row({ item, remove }) {
      const [toggleImpact, setToggleImpact] = useState(true);
      return (
        <div>
          <pre>{JSON.stringify(item, undefined, 2)}</pre>
          <button onClick={() => remove(item.id)}>
            remove
          </button>
          {toggleImpact  ?
          <button onClick={() => setToggleImpact(!toggleImpact)} >
                <p>I'm not set</p>
                </button>
                :
                    <button onClick={() => setToggleImpact(!toggleImpact)} >
                <p>I'm set</p>
                </button>   
          }
        </div>
      );
});

Upvotes: 1

Related Questions