Atarius Armstrong
Atarius Armstrong

Reputation: 13

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;

Upvotes: 1

Views: 1194

Answers (2)

Sahil Raj Thapa
Sahil Raj Thapa

Reputation: 2483

Since you have not passed index as argument to onClick={this.props.removePokemon}.

index inside removePokemon method refers the event object. So the code

team.splice(index, 1) evaluates to team.splice(eventObject, 1).

That's why splice is removing first element of the array.

You can change to onClick={() => this.props.removePokemon(i)}to remove the element you want.

Upvotes: 1

Andrii Golubenko
Andrii Golubenko

Reputation: 5179

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>

Upvotes: 1

Related Questions