N
N
NiyazNA2019-01-31 19:38:33
React
NiyazNA, 2019-01-31 19:38:33

Am I correct in removing an element from a list in React?

Hello! I'm learning React. Read Main Concepts in the documentation. Decided to make a simple tudu sheet. I implemented the removal of a list element like this (by googling):

this.setState(prevState =>({
      todoItems: prevState.todoItems.filter(itemKey => itemKey != deletedItemsKey)
}));

But it's not clear to me, is it really necessary to iterate over the keys of all elements of the list and compare them with the key of the element to be removed in order to remove an element? For example, in native JS, you can simply event.target.parentNode.removeChild(event.target), where event.target is the element to be removed.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-05-01
@NiyazNA

In React, you render a list based on data:

<List>
  {data.map(item => <Item key={item.id} item={item} />)}
</List>

When the state is updated with the immutable removal of the element, the component will be redrawn and the new version of the node tree will be checked against the old one, the elements missing in the new version will be removed from the DOM.
Lists and keys
Reconciliation

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question