Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove item from array in React

Tags:

reactjs

I have problem with removeItem function (it should remove current <li> that button is nested in, and item from array on this.state.list), no code currently because I try so much things of that and nothing working so I end up on console.logs watch what happened so I deleted it

import React, { Component } from 'react';
import './Todo.css';

class Todo extends Component {
    constructor(props) {
        super(props);
        this.state = {
            list: [],
            text: ''
        }
        this.textChange = this.textChange.bind(this);
        this.addToList = this.addToList.bind(this);
        this.removeItem = this.removeItem.bind(this);
    }

    textChange(e) {
        this.setState({
            text: e.target.value
        })
    }

    addToList() {
        this.setState(prevState => ({
            list: prevState.list.concat(this.state.text),
            text: ''
        }))
    }

    removeItem(e) { ?
        ? ? ? ? ? ? ?
    }

    render() {
        return(
          <div>
            <h1>My Todo List</h1>
            <h3>Add item</h3>
            <input value={this.state.text} onChange={e => this.textChange(e)}/>
            <button onClick={this.addToList}>+</button>
            <ul>{this.state.list.map((x,y) => {
              return <li key={y}>{x}
              <button onClick={this.removeItem}>-</button>
              </li>})}
            </ul>
          </div>
        )
    }
}

export default Todo;
like image 631
Dave Wicomo Avatar asked Nov 28 '22 22:11

Dave Wicomo


1 Answers

in my solution eg:

const remove = (i) => {
        const arr = data.filter((item) => item.name !== i);
        setData(arr);
    };

I filtered the items that are not removed and set again the state

like image 61
Hải Anh Nguyễn Avatar answered Dec 10 '22 10:12

Hải Anh Nguyễn