Sam
Sam

Reputation: 505

Get index of element to be deleted in array using .map (Javascript/React)

I have an array of ingredients I want to display as a list in my React app. Associated with each item is a Delete button that when clicked, would remove that specific element from the array and re-render with the updated array.

Is there a way to find the index of the element and pass it onto the handleDelete() function?

Or is the only way to loop through all elements to find and remove?

handleDelete(id) {
   //use id to remove element from the array 
   //setState of newly filtered array 
}


render() {
    var ingredients = ["chicken", "rice"]
    return (

    <ul className="pantry"> 
    {
        ingredients.map((ingred, index) => {
            return <li key={ingred.index}><button onClick={this.handleDelete.bind(this, ingred.index)}>Delete</button>{ ingred }</li>
        })
    } 
    </ul>

    );
}

Upvotes: 0

Views: 2444

Answers (1)

Matthew Herbst
Matthew Herbst

Reputation: 31973

It seems you pretty much have it done. You just need to create a closure in your method and actually return the callback function. You also need to store the ingredients in state. (I've also cleaned the code up a bit.)

constructor(props) {
  super(props);

  this.state = {
    ingredients: ["chicken", "rice"],
  };

  this.handleDelete = this.handleDelete.bind(this);
}

handleDelete(indexToDelete) {
  //use id to remove element from the array 
  //setState of newly filtered array
  return (event) => {
    this.setState((currentState) => {
      const currentIngredients = currentState.ingredients;

      return {
        ingredients: currentIngredients.slice(0, indexToDelete - 1).concat(currentIngredients.slice(i, currentIngredients.length)),
      };
    });
  }; 
}

renderIngredient(ingredient, index) {
  return (
    <li key={ingred}>
      <button onClick={this.handleDelete(index)}>
        Delete
      </button>
      {ingredient}
    </li>
  );
}

render() {
    return (
      <ul className="pantry"> 
      {
        this.state.ingredients.map(this.renderIngredient)
      } 
      </ul>
    );
}

Upvotes: 2

Related Questions