3

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;
Narendra Jadhav
  • 8,799
  • 15
  • 28
  • 38
Dave Wicomo
  • 153
  • 1
  • 1
  • 11
  • 1
    Fetch array from state and remove element using [splice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) function and set state. – sarthak Jan 03 '18 at 12:12
  • 1
    Possible duplicate [delete-item-from-state-array-in-react](https://stackoverflow.com/questions/36326612/delete-item-from-state-array-in-react). – margaretkru Jan 03 '18 at 12:13

8 Answers8

6

Removing item from array by index:

const newList = this.state.list.splice(index, 1);

Removing item from array by value:

const newList = this.state.list.splice(this.state.list.indexOf(value), 1);
denismart
  • 408
  • 3
  • 12
4

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

  • 2
    While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please [include an explanation for your code](https://meta.stackexchange.com/q/114762/269535), as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. You can use the [edit] button to improve this answer to get more votes and reputation! – Brian Tompsett - 汤莱恩 Aug 17 '20 at 10:37
  • i'm sorry that my fault! – Hải Anh Nguyễn Sep 24 '20 at 07:43
3

You can filter your list by the issue you want, and it will be auto removed, for example, if you want to remove all items = 3 :

list: prevState.list.filter(x=> x != 3);

Good luck!

Manzurul Hoque Rumi
  • 2,328
  • 4
  • 14
  • 38
Chag
  • 31
  • 3
2
removeItem(item) {
    const item = getItem(this.state.list, item.id) // Method to get item in list through comparison (IE: find some item with item.id), it has to return ITEM and INDEX in array
    const newlist = [].concat(list) // Clone array with concat or slice(0)
    newlist.splice(item.index, 1);
    this.setState({list: newlist});       
  }
Mosè Raguzzini
  • 12,776
  • 26
  • 36
2

I think you should pass the index of the item to your removeItem function. Like so:

removeItem(index) {
  const list = this.state.list;

  list.splice(index, 1);
  this.setState({ list });
}

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((text, i) => {
          return (
            <li key={i}>
              {text}
              <button onClick={() => this.removeItem(i) }>-</button>
            </li>
          );
        })}
      </ul>
    </div>
  )
}
Krasimir
  • 12,605
  • 3
  • 34
  • 52
1

I would pass the index of the item in the list on click then splice the array:

<ul>
  {
    this.state.list.map((x,y) => {
      return (
        <li key={y}>
          {x}
          <button onClick={() => this.removeItem(y)}>-</button>
        </li>
      );
    })
  }
</ul>

Then in removeItem:

removeItem(index) {
  const list = this.state.list;
  list.splice(index, 1);
  this.setState({ list });
}
Rick
  • 837
  • 6
  • 14
0

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);
  }

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

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

  removeItem(index) {
    let newList = this.state.list.splice(index,1);
    this.setState({list:newList})
  }

  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.bind(this,y)}>-</button>
          </li>})}
        </ul>
      </div>
    )
  }
}

export default Todo;
yogesh agrawal
  • 590
  • 6
  • 14
0
  _deleteTodo(index) {
    console.log("delete " + index);
    this.state.todos.splice(index, 1);
    this.setState({
      todos: this.state.todos.filter(i => i !== index)
    });
  }

I had a problem with splice and i honestly don know why. However this method work for me and you can try it! Ps. If anybody know why splice is not working with state and index please let me know i am curious!

gerald heng
  • 109
  • 2
  • 5