PEEMAPOD NEAMKUR
PEEMAPOD NEAMKUR

Reputation: 159

How to update value array in object React js

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

Answers (1)

bilwit
bilwit

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

Related Questions