Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript React Basics Introducing Props Use Keys to Keep Track of Elements

toString method doesn't work on my keys, returns error

The error I receive is this: Warning: Encountered two children with the same key, `function toString()

Oddly enough, when I remove ".toString" the code compiles and does not return an error.

What's going on?

my app.js code

const players = [
    {
        name: "Guil",
        score: 50,
        id: 0
      },
      {
        name: "Treasure",
        score: 85,
        id: 1
      },
      {
        name: "Ashley",
        score: 95,
        id: 2
      },
      {
        name: "James",
        score: 80,
        id: 3
      }
]

const Header = (props) => {
    console.log(props);
    return (
        <header>
            <h1>{props.title}</h1>
            <span className="stats">Players: {props.totalPlayers}</span>
        </header>
    );
}

// create counter component
const Player = (prop) => {
    return (
        <div className="player">
            <span className="player-name">
                {prop.name}
            </span>

            <Counter 
                score={prop.score}
            />
        </div>
    );
}


const Counter = (prop) => {
    return (
        <div className="counter">
            <button className="counter-action decrement"> - </button>
            <span className="counter-score">{prop.score}</span>
            <button className="counter-action increment"> + </button>
        </div>
    );
}

const App = (prop) => {
return (
    <div className="scoreboard">
        <Header title="Scoreboard" totalPlayers={1}  />

        {/* Players list */}
        {prop.initialPlayers.map( player =>
            <Player 
                name={player.name} 
                score={player.score} 
                key={player.id.toString}
            /> 
        )}

    </div>
);

}

ReactDOM.render(
    <App initialPlayers={players} />,
    document.getElementById('root')
);

1 Answer

Johnny Austen
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Johnny Austen
Front End Web Development Techdegree Graduate 35,455 Points

Hey. It's because your .toString call does not contain any parens after it:

key={player.id.toString}

Should be:

key={player.id.toString()}

Hope this helps.