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 Components (2018) Managing State and Data Flow Adding Items to State

James Crosslin
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
James Crosslin
Full Stack JavaScript Techdegree Graduate 16,882 Points

If you chose to try this course with React hooks, it can start to get tricky here. My solution if you're struggling

I did change a little, like putting in an empty array in anticipation of having to empty it anyway later. I also disliked the index method of locating which player to remove, so I used the players unique ids which feels safer to me.

App.js

import React, { useState } from "react";
import Header from "./Header";
import Player from "./Player";
import AddPlayerForm from "./AddPlayerForm";

function App() {
  const [players, setPlayers] = useState([]);
  const [playerId, setPlayerId] = useState(0);

  const handleScoreChange = (id, addend) => {
    setPlayers((players) => {
      const clone = [...players];
      clone.find((player) => player.id === id).score += addend;
      return clone;
    });
  };

  const handleRemovePlayer = (id) =>
    setPlayers((players) => players.filter((playerObj) => playerObj.id !== id));

  const createId = () => {
    setPlayerId((id) => id + 1);
    return playerId;
  };

  const handleAddPlayer = (name) =>
    setPlayers((players) => {
      const playerObj = {
        name,
        id: createId(),
        score: 0,
      };
      return [...players, playerObj];
    });

  return (
    <div className="scoreboard">
      <Header
        title="Scoreboard"
        totalPlayers={players.length}
        totalScore={[...players].reduce((acc, player) => acc + player.score, 0)}
      />

      {/* Players List */}
      {players.map((player) => (
        <Player
          {...player}
          key={player.id.toString()}
          removePlayer={handleRemovePlayer}
          changeScore={handleScoreChange}
        />
      ))}
      <AddPlayerForm addPlayer={handleAddPlayer} />
    </div>
  );
}

export default App;

AddPlayerForm.js

import React, { useState } from "react";

function AddPlayerForm(props) {
  const [nameField, setNameField] = useState("");
  const {addPlayer} = props;
  const handleNameFieldChange = (e) => setNameField(e.target.value);

  const handleSubmit = (e) => {
    e.preventDefault();
    addPlayer(nameField)
    setNameField("");
  };

  return (
    <form onSubmit={ handleSubmit }>
      <input
        type="text"
        value={nameField}
        onChange={handleNameFieldChange}
        placeholder="Enter a player's name"
      />

      <input type="submit" value="Add Player" />
    </form>
  );
}

export default AddPlayerForm;