Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript React Basics (2018) Understanding State Remove Items From State

removePlayer function not working

My code isn't producing the intended result, the players names are not being removed from the array when I click the "x" next to their name.

const Player = (props) => {
    return (
        <div className='player'>
            <span className='player-name'>
            <button className="remove-player" onClick={ () => props.removePlayer(props.id) }></button>
                {props.name}
            </span>
            <Counter />
        </div>
    )
}

class App extends React.Component {

    state = {
        players: [
            {
                name: "Guil",
                id: 1
            },
            {
                name: "Treasure",
                id: 2
            },
            {
                name: "Ashley",
                id: 3
            },
            {
                name: "James",
                id: 4
            }
        ]
    };

    handleRemovePlayer = (id) => {
        this.setState( prevState => {
            return {
                player: prevState.players.filter( p => p.id !== id )
            };
        });
    }

    render () {
        return (
            <div className='scoreboard'>
                <Header title="Scoreboard" totalPlayers={this.state.players.length} />

                {/* player list */}
                {this.state.players.map(player =>
                    <Player 
                     name={player.name}
                     id={player.id} 
                     key={player.id.toString()} 
                     removePlayer={this.handleRemovePlayer}
                    />
                )}
            </div>
        );
    }
}


ReactDOM.render(<App />, document.getElementById('root'));

1 Answer

I fixed it. On this line, I typed "player" instead of "players"

The code is working normally.

return {
                player: prevState.players.filter( p => p.id !== id )
            };