Reputation: 159
How to update value array in object React js I want update value checked by name .....................................................................................................................................................................................................................................................................................................
const [state, setState] = React.useState([{
name: "box",
checked: false,
},{
name: "box1",
checked: false,
}]);
const checkboxhandleChange= (event) => {
setState({ ...state, [event.target.name]: event.target.checked });
};
Upvotes: 0
Views: 97
Reputation: 819
In the general case of updating an array of objects, it would be better to use map
instead of trying to use a solution based on spread
so that you preserve the original list of elements without adding new ones.
setState(
state.map((item) => item.name === event.target.name ? { ...item, checked: event.target.checked } : item)
);
What you are doing now is replacing the initial array in state
to a single object.
For your specific case, you may also consider using an object
instead which might be a more elegant solution given what has been shared thus far.
const [state, setState] = React.useState({
box: false,
box1: false,
})
const checkboxhandleChange = (event) => {
setState({
...state,
[event.target.name]: event.target.checked
})
};
Upvotes: 2