skip to Main Content

I have a steate with an array of objects:

const [Value, setValue] = useState([
   { value1: false, value2: false, value3: false },
   { value1: false, value2: false, value3: false },
   { value1: false, value2: false, value3: false }
]);

And using the map method, I render a div for each object:

{Value.map((item, i) => {
    return (
      <div
        key={i}
        onClick={() => {
          setValue((oldArr) => {
            let newArr = [...oldArr];
            newArr[i].value3 = true;
            return newArr;
          });
        }}
      >
        {item.value3 ? 'yes' : 'no'}
      </div>
    );
})}

And then I click to assign the true to the key value3 of the current object.

But I can’t figure out how I should assign the false to all other keys value3 from other objects on this click. Exactly, I want to click and get true for current key value3 and all other value3 get false.

Help me pls!

2

Answers


  1. You can achieve this by first updating all the value3 properties to false in the onClick handler, and then setting the value3 of the clicked item to true. Here’s how you can modify your onClick handler:-

    onClick={() => {
      setValue((oldArr) => {
        let newArr = oldArr.map((item, index) => {
          return {
            ...item,
            value3: index === i ? true : false
          };
        });
        return newArr;
      });
    }}
    
    Login or Signup to reply.
  2. For one thing, this is mutating state:

    newArr[i].value3 = true;
    

    Definitely don’t do that. We can solve both this and the issue at hand by projecting these array elements into a new array, setting other values to false and the target value to true. For example:

    setValue((oldArr) => oldArr.map((a, x) => ({
      ...a,
      value3: x === i ? true : false
    }));
    

    What this does is map over the existing array, constructing new objects which contain all properties of the existing objects and a manual value for value3, which is true if the index of the array matches i and false otherwise.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search