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
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:-
For one thing, this is mutating state:
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 totrue
. For example: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 istrue
if the index of the array matchesi
andfalse
otherwise.