Ben Swindells
Ben Swindells

Reputation: 269

React Removing an item from a to do list

i'm creating a simple react to do list, I'm currently working on a delete button, I have created an array then passed this array into a prop, I then need to splice that item from the prop array when the user clicks the delete button. I was able to store the array number but I cant seem to update the array after its deleted.

CLASS CALL:

 <TodoList items={this.state.items} deleteItems={this.deleteItem}/>

SUB-CLASS CODE:

class TodoList extends Component {
  constructor(props) {
    super(props);
    this.removeItem = this.removeItem.bind(this);

  }

  render() {

    return (
      <div>  
        { this.props.items.map((item, i) => (
          <div className={"col-12"} key={item.id}>
            <div className={"card text-white"}>
              <div className={item.priority}>
                <div className={"col-12 card-body"}>
                  <h1>{item.title}</h1>
                  <p>{item.text}</p>
                  <button onClick={() => { this.removeItem(item, i)}} key={i} className={"col-12 btn btn-primary bg-red"}>Delete</button> 
                </div>         
              <div/>
            </div>
          </div>
        </div>
        ))}
      </div>

    );

  }
  removeItem(e, i) {
    this.props.items.splice(i, '');
    console.log(i);
  }
}

I have been looking at different stack questions but none of the solutions seem to apply to this, thanks for any constructive feedback :)

Upvotes: 1

Views: 1861

Answers (1)

Brian Le
Brian Le

Reputation: 2686

I believe <TodoList /> component should have its own state. However, if you can't do so, there's 2 solutions to this problem:

  • Keep <ToDoList /> component's state and props in sync (In case the parent component modifies the state passed down as items). Then modify the <TodoList /> 's state.
  • Declare a method that removes the item inside the parent component which has the state, and pass it down as props (Recommended)

Example code:

class ParentComponent extends Component {
  state = {   
    items: [1, 2, 3]
  }

  removeItem = index => () => {
    this.setState(prevState => ({
      items: prevState.items.filter((_, i) => i !== index) //Filter the items
    }));
  };

  render() {
    return (
     <TodoList items={this.state.items} deleteItems={this.removeItem} />
    );
  }
}

Important: Always use pure functions to modify the state. Do not use .splice() or .push() (If you haven't cloned the state yet). It's always safer to use .filter(), .map(), .concat(), etc.

Upvotes: 5

Related Questions