1

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;
3
  • 1
    onClick={this.props.removePokemon} vs function removePokemon (index) { ... } - What's missing on the left side? Commented May 28, 2019 at 15:22
  • Try adding some logging to your function - i.e. console.log to check what value index is, I believe that is where the issue lies. Commented May 28, 2019 at 15:22
  • 1
    If you are new to React, take a look at debugging, but since this is a small problem, you could simply do a console.log(index) in removePokemon. Commented May 28, 2019 at 15:26

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

index won't be undefined but an event object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.