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 Update State Based on a Player's Index

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

Disagree with the new index prop, also my solution uses Hooks instead of classes

When we started creating our player objects, we specifically gave them id properties that were different from each other in order to identify them. To me, it makes sense to use those id's to find the value instead of pass another prop.

Also, I used React Hooks for functional code instead of ES6 classes.

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

function App() {
  const playerArr = [
    { name: "Guil", id: 1, score: 0 },
    { name: "Treasure", id: 2, score: 0 },
    { name: "Ashley", id: 3, score: 0 },
    { name: "James", id: 4, score: 0 },
  ];

  const [players, setPlayers] = useState(playerArr);

  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));

  return (
    <div className="scoreboard">
      <Header title="Scoreboard" totalPlayers={players.length} />

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

export default App;

2 Answers

Sweet! I did the same with the index topic you mention. Also in the react docs says that you have to use index as a last resource. Thanks for sharing!

Joe Elliot
Joe Elliot
5,330 Points

Yeah I did wonder why we weren't just using the player IDs.....

I don't know anything about React Loops though, I assume that's coming later in the course.