Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splice is removing the last element of array not index - React

Tags:

reactjs

I want each note to have a delete button that when clicked removes that note from an array in my state but .splice is removing the last element not the index.

I added an alert statement to verify index is correct. The alert says the correct number but the splice removes the last element. Why is this happening?

constructor(props) {
        super(props);
        this.state = {
            Notes: ["1","2","3","4"]
        }
    }

    addNote = () => {
        var noteList = [...this.state.Notes];
        var newNote = "";
        this.setState({ Notes: noteList.concat(newNote) });
    }

    deleteNote = (index) => {
        var noteList = [...this.state.Notes];
        alert(index);
        noteList.splice(index, 1);
        this.setState({ Notes: noteList });
    }

    renderNotes(Notes) {
        return (
            <div>
                {Notes.map((Note, index) =>
                    <div class="note">
                        <div class="noteTop">
                            <button id="menu"><FontAwesomeIcon icon={faEllipsisV} /></button>
                            <button id="delete" onClick={() => this.deleteNote(index)}><FontAwesomeIcon icon={faTimes} /></button>
                        </div>
                        <textarea class="noteMain">{Note}</textarea>
                    </div>
                )}
            </div>
        );
    }
like image 908
Bri Liston Avatar asked Nov 21 '25 15:11

Bri Liston


1 Answers

A couple of things at issue here.

First, you're rendering an array of elements that you modify but aren't using a key on the divs you're rendering (see: https://reactjs.org/docs/lists-and-keys.html#keys). Your console should show a warning "Warning: Each child in a list should have a unique "key" prop.". If you add a key to the div, it'll render correctly with your code as-is. The note itself makes for a unique key in your example although you may want to change it later to something that doesn't assume unique note values. Codepen: https://codesandbox.io/s/eager-cray-41dv7

<div className="note" key={Note}>

Second, but not as important after the first fix but will affect you later when you want to let people update the note: React doesn't support children in <textarea> elements. See https://reactjs.org/docs/forms.html#the-textarea-tag.

If you change your text area code the below, you'll see the updates reflected correctly in the UI and it'll later be useful when you enable editing.

<textarea className="noteMain" value={Note} />
like image 170
Michael Flores Avatar answered Nov 24 '25 22:11

Michael Flores



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!