H
H
HalvinBRO2021-07-01 05:36:08
React
HalvinBRO, 2021-07-01 05:36:08

How to remove an element from an array in React?

I wrote a code to remove an array element, but it does not work correctly. After pressing the delete button, the element on which the button was pressed and all other elements in the array that come after the element on which the button was pressed are deleted. I’ll clarify right away that I have two components: a functional one, where the array itself is mapped and the delete function is located; class, where the code is written for each element of the array.
Element I delete through "slices".
Who fumbles, help!

Here is a piece of code from a functional component:

...
const [notes, setNotes] = React.useState([]);
...
function removeNote(index) {
    setNotes([...notes.slice(0, index), ...notes.slice(index + 1)]);
  }
...
return (
...
<div className="table__list">
        {notes.map((note, i) => (
          <Note 
            key={i} 
            id={i} 
            text={note}
            handleDeleteNote={() => removeNote(i)}
          />
        ))}
      </div>
...
);
...


Here is part of the code from the class component:
...
class Note extends React.Component {
  constructor(props) {
    super(props);

    this.id = props.id;
    this.text = props.text;
    this.notes = props.notes;
    this.removeNote = props.handleDeleteNote;
...
 render() {
    return (
...
<button className="removeBtn" onClick={this.removeNote}></button>
...
);}
...

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question