2

I have no experience with js and suggested to learn React before React Native. My question comes from code from Intro to React's tutorial.

In tutorial, we made a list named history, with move as its key.

class Game extends React.Component {
  constructor() {
    super();
     this.state = {
      history: [{
        squares: Array(9).fill(null)
      }],
      xIsNext: true,
      stepNumber: 0,
    };
  }

  [...]

  render() {
    [...]

    const moves = history.map((step, move) => {
      const desc = move ?
        'Move #' + move :
        'Game start';
      return (
        <li key={move}>
          <a href="#" onClick={() => this.jumpTo(move)}>{desc}</a>
        </li>
      );
    });

[...]

The explanation for that part was

[...] React asks you to specify a key property on each element in a list, a string to differentiate each component from its siblings. In this case, alexa, ben, claudia might be sensible keys; if the items correspond to objects in a database, the database ID is usually a good choice:

<li key={user.id}>{user.name}: {user.taskCount} tasks left</li>

[...] It's strongly recommended that you assign proper keys whenever you build dynamic lists. If you don't have an appropriate key handy, you may want to consider restructuring your data so that you do. [...] If you don't specify any key, React will warn you and fall back to using the array index as a key – [...]

Now what I'm confused about, what is move on history above? I can't see anything implying move is assigned a value, yet when it's printed, it shows list index? How come?

1
  • 1
    I'd strongly consider learning JS before trying to learn a framework that relies heavily on knowing JS. Commented Nov 14, 2016 at 8:27

1 Answer 1

6

The list is being created by using a map method to 'map over' the history array. map will call a function for each element in the array; the second parameter to this callback function is the index of the element in the array.

In your code the callback function looks like this:

(step, move) => {
  const desc = move ?
    'Move #' + move :
    'Game start';
  return (
    <li key={move}>
      <a href="#" onClick={() => this.jumpTo(move)}>{desc}</a>
    </li>
  );
}

and therefore the index of the array, the second parameter, is called move (you could call it anything); the value of this is then rendered as they key property for each list item.

Description of map here

Sign up to request clarification or add additional context in comments.

2 Comments

So... is step the current value? But just not used?
nvm finally I understand. Thank you very much, your explanation and link truly a big help!

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.