How to get index of clicked dynamically added Component in React and remove it?

Viewed 535

I created a custom component <Card />. On the main page, I have add a button which will add these cards once the cards are added each card have a specific remove button which should remove that specific card from a bunch of cards.

Here is my code:

Add function to add cards:

    handleAddComponent() {
    this.setState({
      component: [
        ...this.state.component,
        <Card remove={this.handleRemoveRow} />
      ]
    });
  }

Remove function to remove cards:

    handleRemoveRow(event) {
    // console.log(event.target.);
    this.setState({
      component: this.state.component.slice(0, -1)
    });
  }

and the render:

    render() {
    return (
      <section>
        {this.state.component}
        <button onClick={this.handleAddComponent}>
          <span>Add</span>
        </button>
      </section>
    );
  }

The issue with this code is whenever I click the remove button only the last component is removed which doesn't meet my condition, I want to remove a particular card. component: this.state.component.slice(0, -1) this removes the last component.

Is there any other way I can get the index of each card component so I can remove a particular card?

2 Answers
 handleAddComponent() {
    this.setState({
      component: [
        ...this.state.component,
        <Card remove={() => this.handleRemoveRow(this.state.component.length)} />
      ]
    });
  }
 handleRemoveRow = i => {
    this.setState({
      component: this.state.component.filter((el, j) => j === i)
    });
  }

I have made few changes as below :

cardId = 0; // To handle all the cards, maintaining at app level

{
    cardId : // <--- To maintain the index, and easily remove the component with id 
    card : <Card
              key={this.cardId}
              cardId={this.cardId} //<--- Passing cardId as props so we can get the same value while removing
              remove={this.handleRemoveRow}
            />
}

App.js :

  handleAddComponent() {
    this.cardId++;
    this.setState({
      component: [
        ...this.state.component,
        { cardId : this.cardId , card : <Card key={this.cardId} cardId={this.cardId} remove={this.handleRemoveRow} />}
      ]
    });
  }

  handleRemoveRow(cardId) {
    let card = [...this.state.component];
    card = card.filter(card => card.cardId !== cardId)
    this.setState({
      component: card
    });
  }
{this.state.component.map(({card}) => card)}

Card.js

<button onClick={() => this.props.remove(this.props.cardId)}>
    <span>Remove</span>
</button>

WORKING DEMO :

Edit so-remove-dynamic-added

Related