Search code examples
javascriptarraysreactjsstatesplice

Why is splice method removing only first array index in React?


I'm making a small application in React with the PokeAPI and am having issues with using the splice() method to remove an element (pokemon) from the array (team). No matter which element I pick to remove it only removes the first element in the array.

This is the function -- which is being passed down through props -- I'm using in order to delete the item.

removePokemon = (index) => {
  const team = [...this.state.team]
   team.splice(index, 1)
   this.setState({team})
  }

And here is the Team component where it's actually being used.

import React, { Component } from 'react';
import Button from 'react-bootstrap/Button'


class Team extends Component {
    render() {
        return (
            <div>
                <h2>{this.props.trainer && <p>{this.props.trainer}'s Team</p>}</h2>
                {this.props.team &&
                <div>
                    {this.props.team.map((pokemon, i) => (
                        <div key={pokemon.id}>
                            <span className='cardHeader'>#{pokemon.id} - {pokemon.name}</span>
                            <img src={pokemon.sprites.front_default} alt={pokemon.name}/>
                            <Button onClick={this.props.removePokemon}>Remove from team</Button>
                        </div>
                    ))}
                </div>
                }

            </div>
        );
    }
}

export default Team;

Solution

  • You don't pass an argument index to your function removePokemon:

    You need to edit one row:

    <Button onClick={() => this.props.removePokemon(i)}>Remove from team</Button>