Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove a property from state object in React?

Here are properties of state object:

  const [items, setItems] = useState({
    key1: 'apple',
    key2: 'watermelon',
    key3: 'banana',
  });

I wonder, how I can delete specific property from this state object by handling delete?

 const handleDelete = (e) => { }

Thanks in advance

like image 972
Leonardo Avatar asked Sep 11 '25 14:09

Leonardo


1 Answers

Here's one way: duplicate the object (so React notices the change), delete the key (maybe this is the JavaScript feature you were missing), and set the state.

const handleDelete = (e) => {
  const newItems = {...items};
  delete newItems.key2; // or whichever key you want
  setItems(newItems);
}

I'm curious whether there's an Object helper to do this all in one line.

@Wyck found a cleaner way, which uses the "rest" aspect of destructuring assignment:

const handleDelete = (e) => {
  const {key2, ...newItems} = items; // newItems gets all but key2
  setItems(newItems);
}
like image 142
edemaine Avatar answered Sep 13 '25 03:09

edemaine