[Tutorial] Make it easier to follow the instructions (#9454)
* tutorial: adds note about onClick
* tutorial: show full square component
* merge
* fixes line number
* tutorial: misc changes
* fixes Board render initial code sample
* [tutorial] adds codepen links and misc small fixes
* removes useless arrow functions, #9531
* {this.renderSquare} new lines
* be more explicit about history state
* fixes highlight
* following along locally
* changes todo to this.props.value
* removes calculateWinner from initial codepens and includes it in tutorial
* removes note about calculateWinner at end of file
* adds debug-view and debug-view-final
* removes debug view, updates codepen instructions
* adds another codepen
* tutorial.md
* tutorial.md
* tutorial.md
* tutorial.md
* Put . into links for consistency with docs
* Make the very first change easier to follow
* A few more changes
Today, we're going to build an interactive tic-tac-toe game.
If you like, you can check out the final result here: <ahref="https://codepen.io/gaearon/pen/VbvBWg?editors=0010"target="_blank">Final Result</a>. Try playing the game. You can also click on a link in the move list to go "back in time" and see what the board looked like just after that move was made.
If you like, you can check out the final result here: [Final Result](https://codepen.io/gaearon/pen/gWWZgR?editors=0010). Try playing the game. You can also click on a link in the move list to go "back in time" and see what the board looked like just after that move was made.
### Prerequisites
@ -30,17 +30,19 @@ If you need a refresher on JavaScript, we recommend reading [this guide](https:/
#### Following Along in Browser
We'll be using an online editor called CodePen in this guide. You can begin by opening this <ahref="https://codepen.io/gaearon/pen/JNYBEZ?editors=0010"target="_blank">starter code</a>. It should display an empty tic-tac-toe field. We will be editing that code during this tutorial.
We'll be using an online editor called CodePen in this guide. You can begin by opening this [starter code](https://codepen.io/gaearon/pen/oWWQNa?editors=0010). It should display an empty tic-tac-toe field. We will be editing that code during this tutorial.
#### Following Along Locally
You can also follow along locally if you don't mind a few extra steps:
Alternatively, you can set up a project on your computer.
This is more work, but gives you a standard development environment, including support for [modules](https://medium.freecodecamp.com/javascript-modules-a-beginner-s-guide-783f7d7a5fcc).
1. Make sure you have a recent version of [Node.js](https://nodejs.org/en/) installed.
2. Follow the [installation instructions](/react/docs/installation.html#creating-a-new-application) to create a new project.
3. Delete all files in the `src/` folder of the new project.
4. Add a file named `index.css` in the `src/` folder with <ahref="https://codepen.io/gaearon/pen/JNYBEZ?editors=0100"target="_blank">this CSS code</a>.
5. Add a file named `index.js` in the `src/` folder with <ahref="https://codepen.io/gaearon/pen/JNYBEZ?editors=0010"target="_blank">this JS code</a>, and then add three lines to the top of it:
4. Add a file named `index.css` in the `src/` folder with [this CSS code](https://codepen.io/gaearon/pen/oWWQNa?editors=0100).
5. Add a file named `index.js` in the `src/` folder with [this JS code](https://codepen.io/gaearon/pen/oWWQNa?editors=0010), and then add three lines to the top of it:
```js
import React from 'react';
@ -54,7 +56,7 @@ Now if you run `npm start` in the project folder and open `http://localhost:3000
If you get stuck, check out the [community support resources](https://facebook.github.io/react/community/support.html). In particular, [Reactiflux chat](/react/community/support.html#reactiflux-chat) is a great way to get quick help. If you don't get a good answer anywhere, please file an issue, and we'll help you out.
You can also look at the <ahref="https://codepen.io/gaearon/pen/VbvBWg?editors=0010"target="_blank">final version of the code</a>.
You can also look at the [final version of the code](https://codepen.io/gaearon/pen/gWWZgR?editors=0010).
[See full expanded version.](https://babeljs.io/repl/#?babili=false&evaluate=false&lineWrap=false&presets=react&targets=&browsers=&builtIns=false&debug=false&experimental=false&loose=false&spec=false&playground=true&code=%3Cdiv%20className%3D%22shopping-list%22%3E%0A%20%20%3Ch1%3EShopping%20List%20for%20%7Bprops.name%7D%3C%2Fh1%3E%0A%20%20%3Cul%3E%0A%20%20%20%20%3Cli%3EInstagram%3C%2Fli%3E%0A%20%20%20%20%3Cli%3EWhatsApp%3C%2Fli%3E%0A%20%20%20%20%3Cli%3EOculus%3C%2Fli%3E%0A%20%20%3C%2Ful%3E%0A%3C%2Fdiv%3E)
If you're curious, `createElement()` is described in more detail in the [API reference](/react/docs/react-api.html#createelement), but we won't be using it directly in this tutorial. Instead, we will keep using JSX.
You can put any JavaScript expression within braces inside JSX. Each React element is a real JavaScript object that you can store in a variable or pass around your program.
@ -106,7 +110,7 @@ The `ShoppingList` component only renders built-in DOM components, but you can c
### Getting Started
Start with this example: <ahref="https://codepen.io/gaearon/pen/JNYBEZ?editors=0010"target="_blank">Starter Code</a>.
Start with this example: [Starter Code](https://codepen.io/gaearon/pen/oWWQNa?editors=0010).
It contains the shell of what we're building today. We've provided the styles so you only need to worry about the JavaScript.
@ -118,11 +122,32 @@ In particular, we have three components:
The Square component renders a single `<button>`, the Board renders 9 squares, and the Game component renders a board with some placeholders that we'll fill in later. None of the components are interactive at this point.
(The end of the JS file also defines a helper function `calculateWinner` that we'll use later.)
### Passing Data Through Props
Just to get our feet wet, let's try passing some data from the Board component to the Square component. In Board's `renderSquare` method, change the code to return `<Square value={i} />` then change Square's render method to show that value by replacing `{/* TODO */}` with `{this.props.value}`.
Just to get our feet wet, let's try passing some data from the Board component to the Square component.
In Board's `renderSquare` method, change the code to pass a `value` prop to the Square:
```js{3}
class Board extends React.Component {
renderSquare(i) {
return <Squarevalue={i}/>;
}
```
Then change Square's `render` method to show that value by replacing `{/* TODO */}` with `{this.props.value}`:
```js{5}
class Square extends React.Component {
render() {
return (
<buttonclassName="square">
{this.props.value}
</button>
);
}
}
```
Before:
@ -132,21 +157,33 @@ After: You should see a number in each square in the rendered output.
[View the current code.](https://codepen.io/gaearon/pen/aWWQOG?editors=0010)
### An Interactive Component
Let's make the Square component fill in an "X" when you click it. Try changing the button tag returned in the `render()` function of the `Square` class to:
Let's make the Square component fill in an "X" when you click it. Try changing the button tag returned in the `render()` function of the Square like this:
This uses the new JavaScript arrow function syntax. If you click on a square now, you should get an alert in your browser.
If you click on a square now, you should get an alert in your browser.
React components can have state by setting `this.state` in the constructor, which should be considered private to the component. Let's store the current value of the square in state, and change it when the square is clicked. First, add a constructor to the class to initialize the state:
This uses the new JavaScript [arrow function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions) syntax. Note that we're passing a function as the `onClick` prop. Doing `onClick={alert('click')}` would alert immediately instead of when the button is clicked.
```javascript
React components can have state by setting `this.state` in the constructor, which should be considered private to the component. Let's store the current value of the square in state, and change it when the square is clicked.
First, add a constructor to the class to initialize the state:
```javascript{2-7}
class Square extends React.Component {
constructor() {
super();
@ -154,24 +191,51 @@ class Square extends React.Component {
In JavaScript classes, you need to explicitly call `super();` when defining the constructor of a subclass.
In [JavaScript classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), you need to explicitly call `super();` when defining the constructor of a subclass.
Now change the `render` method to display `this.state.value` instead of `this.props.value`, and change the event handler to be `() => this.setState({value: 'X'})` instead of the alert:
Now change the Square `render` method to display the value from the current state, and to toggle it on click:
```javascript
* Replace `this.props.value` with `this.state.value` inside the `<button>` tag.
* Replace the `() => alert()` event handler with `() => setState({value: 'X'})`.
Whenever `this.setState` is called, an update to the component is scheduled, causing React to merge in the passed state update and rerender the component along with its descendants. When the component rerenders, `this.state.value` will be `'X'` so you'll see an X in the grid.
If you click on any square, an X should show up in it.
[View the current code.](https://codepen.io/gaearon/pen/VbbVLg?editors=0010)
### Developer Tools
The React Devtools extension for [Chrome](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en) and [Firefox](https://addons.mozilla.org/en-US/firefox/addon/react-devtools/) lets you inspect a React component tree in your browser devtools.
@ -180,7 +244,12 @@ The React Devtools extension for [Chrome](https://chrome.google.com/webstore/det
It lets you inspect the props and state of any of the components in your tree.
It doesn't work great on CodePen because of the multiple frames, but if you log in to CodePen and confirm your email (for spam prevention), you can go to Change View > Debug to open your code in a new tab, then the devtools will work. It's fine if you don't want to do this now, but it's good to know that it exists.
After installing it, you can right-click any element on the page, click "Inspect" to open the developer tools, and the React tab will appear as the last tab to the right. However, there are a few extra steps to get it working with CodePen:
1. Log in or register and confirm your email (required to prevent spam).
2. Click the "Fork" button.
3. Click "Change View" and then choose "Debug mode".
4. In the new tab that opens, the devtools should now have a React tab.
## Lifting State Up
@ -192,9 +261,9 @@ Instead, the best solution here is to store this state in the Board component in
**When you want to aggregate data from multiple children or to have two child components communicate with each other, move the state upwards so that it lives in the parent component. The parent can then pass the state back down to the children via props, so that the child components are always in sync with each other and with the parent.**
Pulling state upwards like this is common when refactoring React components, so let's take this opportunity to try it out. Add an initial state for Board containing an array with 9 nulls, corresponding to the 9 squares:
Pulling state upwards like this is common when refactoring React components, so let's take this opportunity to try it out. Add a constructor to the Board and set its initial state to contain an array with 9 nulls, corresponding to the 9 squares:
```javascript
```javascript{2-7}
class Board extends React.Component {
constructor() {
super();
@ -202,6 +271,33 @@ class Board extends React.Component {
squares: Array(9).fill(null),
};
}
renderSquare(i) {
return <Squarevalue={i}/>;
}
render() {
return (
<div>
<divclassName="status">{status}</div>
<divclassName="board-row">
{this.renderSquare(0)}
{this.renderSquare(1)}
{this.renderSquare(2)}
</div>
<divclassName="board-row">
{this.renderSquare(3)}
{this.renderSquare(4)}
{this.renderSquare(5)}
</div>
<divclassName="board-row">
{this.renderSquare(6)}
{this.renderSquare(7)}
{this.renderSquare(8)}
</div>
</div>
);
}
}
```
@ -215,26 +311,59 @@ We'll fill it in later so that a board looks something like
]
```
Pass the value of each square down:
Board's `renderSquare` method currently looks like this:
```javascript
renderSquare(i) {
return <Squarevalue={i}/>;
}
```
Modify it to pass a `value` prop to Square.
```javascript{2}
renderSquare(i) {
return <Squarevalue={this.state.squares[i]}/>;
}
```
And change Square to use `this.props.value` again. Now we need to change what happens when a square is clicked. The Board component now stores which squares are filled, which means we need some way for Square to update the state of Board. Since component state is considered private, we can't update Board's state directly from Square. The usual pattern here is pass down a function from Board to Square that gets called when the square is clicked. Change `renderSquare` again so that it reads:
[View the current code.](https://codepen.io/gaearon/pen/gWWQPY?editors=0010)
Now we need to change what happens when a square is clicked. The Board component now stores which squares are filled, which means we need some way for Square to update the state of Board. Since component state is considered private, we can't update Board's state directly from Square.
The usual pattern here is pass down a function from Board to Square that gets called when the square is clicked. Change `renderSquare` in Board again so that it reads:
```javascript{5}
renderSquare(i) {
return (
<Square
value={this.state.squares[i]}
onClick={() => this.handleClick(i)}
/>
);
}
```
Now we're passing down two props from Board to Square: `value` and `onClick`. The latter is a function that Square can call. So let's replace the `this.setState()` call we used to have inside the button click handler in Square's `render()` with a call to `this.props.onClick()`:
We split the returned element into multiple lines for readability, and added parens around it so that JavaScript doesn't insert a semicolon after `return` and break our code.
```javascript
Now we're passing down two props from Board to Square: `value` and `onClick`. The latter is a function that Square can call. Let's make the following changes to Square:
* Replace `this.state.value` with `this.props.value` in Square's `render`.
* Replace `this.setState()` with `this.props.onClick()` in Square's `render`.
* Delete `constructor` definition from Square because it doesn't have state anymore.
After these changes, the whole Square component looks like this:
Now when the square is clicked, it calls the `onClick` function that was passed by Board. Let's recap what happens here:
@ -242,26 +371,70 @@ Now when the square is clicked, it calls the `onClick` function that was passed
1. The `onClick` prop on the built-in DOM `<button>` component tells React to set up a click event listener.
2. When the button is clicked, React will call the `onClick` event handler defined in Square's `render()` method.
3. This event handler calls `this.props.onClick()`. Square's props were specified by the Board.
4. This is how we get into `onClick` passed from the Board, which runs `this.handleClick()` on the Board.
5. We have not defined `this.handleClick` on the Board yet, so the code crashes.
4. Board passed `onClick={() => this.handleClick(i)}` to Square, so, when called, it runs `this.handleClick(i)` on the Board.
5. We have not defined the `handleClick()` method on the Board yet, so the code crashes.
Note that `onClick` on the DOM `<button>` component has a special meaning to React, but we could have called `onClick` prop in Square and `handleClick` in Board something else. It is, however, a common convention in React apps to use `on*` names for the handler prop names and `handle*` for their implementations.
Try clicking a square – you should get an error because we haven't defined `handleClick` yet. Add it to the Board class:
Try clicking a square – you should get an error because we haven't defined `handleClick` yet. Add it to the Board class.
```javascript{9-13}
class Board extends React.Component {
constructor() {
super();
this.state = {
squares: Array(9).fill(null),
};
}
```javascript
handleClick(i) {
const squares = this.state.squares.slice();
squares[i] = 'X';
this.setState({squares: squares});
}
renderSquare(i) {
return (
<Square
value={this.state.squares[i]}
onClick={() => this.handleClick(i)}
/>
);
}
render() {
const status = 'Next player: X';
return (
<div>
<divclassName="status">{status}</div>
<divclassName="board-row">
{this.renderSquare(0)}
{this.renderSquare(1)}
{this.renderSquare(2)}
</div>
<divclassName="board-row">
{this.renderSquare(3)}
{this.renderSquare(4)}
{this.renderSquare(5)}
</div>
<divclassName="board-row">
{this.renderSquare(6)}
{this.renderSquare(7)}
{this.renderSquare(8)}
</div>
</div>
);
}
}
```
[View the current code.](https://codepen.io/gaearon/pen/ybbQJX?editors=0010)
We call `.slice()` to copy the `squares` array instead of mutating the existing array. Jump ahead a [section](/react/tutorial/tutorial.html#why-immutability-is-important) to learn why immutability is important.
Now you should be able to click in squares to fill them again, but the state is stored in the Board component instead of in each Square, which lets us continue building the game. Note how whenever Board's state changes, the Square components rerender automatically.
Square no longer keeps its own state; it receives its value from its parent `Board` and informs its parent when it's clicked. We call components like this **controlled components**.
Square no longer keeps its own state; it receives its value from its parent Board and informs its parent when it's clicked. We call components like this **controlled components**.
The end result is the same but by not mutating (or changing the underlying data) directly we now have an added benefit that can help us increase component and overall application performance.
#### Easier Undo/Redo and Time Travel
Immutability also makes some complex features much easier to implement. For example, further in this tutorial we will implement time travel between different stages of the game. Avoiding data mutations lets us keep a reference to older versions of the data, and switch between them if we need to.
#### Tracking Changes
Determining if a mutated object has changed is complex because changes are made directly to the object. This then requires comparing the current object to a previous copy, traversing the entire object tree, and comparing each variable and value. This process can become increasingly complex.
Determining how an immutable object has changed is considerably easier. If the object being referenced is different from before, then the object has changed. That's it.
#### Determining When To Re-render in React
#### Determining When to Re-render in React
The biggest benefit of immutability in React comes when you build simple _pure components_. Since immutable data can more easily determine if changes have been made it also helps to determine when a component requires being re-rendered.
To learn how you can build *pure components* take a look at [shouldComponentUpdate()](https://facebook.github.io/react/docs/update.html). Also, take a look at the [Immutable.js](https://facebook.github.io/immutable-js/) library to strictly enforce immutable data.
To learn more about `shouldComponentUpdate()` and how you can build *pure components* take a look at [Optimizing Performance](/react/docs/optimizing-performance.html#examples).
### Functional Components
Back to our project, you can now delete the `constructor` from `Square`; we won't need it any more. In fact, React supports a simpler syntax called **stateless functional components** for component types like Square that only consist of a `render` method. Rather than define a class extending React.Component, simply write a function that takes props and returns what should be rendered:
We've removed the constructor, and in fact, React supports a simpler syntax called **functional components** for component types like Square that only consist of a `render` method. Rather than define a class extending `React.Component`, simply write a function that takes props and returns what should be rendered.
Replace the whole Square class with this function:
You'll need to change `this.props` to `props` both times it appears. Many components in your apps will be able to be written as functional components: these components tend to be easier to write and React will optimize them more in the future.
While we're cleaning up the code, we also changed `onClick={() => props.onClick()}` to just `onClick={props.onClick}`, as passing the function down is enough for our example. Note that `onClick={props.onClick()}` would not work because it would call `props.onClick` immediately instead of passing it down.
[View the current code.](https://codepen.io/gaearon/pen/QvvJOv?editors=0010)
### Taking Turns
An obvious defect in our game is that only X can play. Let's fix that.
Let's default the first move to be by 'X'. Modify our starting state in our `Board` constructor.
Let's default the first move to be by 'X'. Modify our starting state in our Board constructor.
```javascript
```javascript{6}
class Board extends React.Component {
constructor() {
super();
this.state = {
// ...
squares: Array(9).fill(null),
xIsNext: true,
};
}
```
Each time we move we shall toggle `xIsNext` by flipping the boolean value and saving the state. Now update our`handleClick` function to flip the value of `xIsNext`.
Each time we move we shall toggle `xIsNext` by flipping the boolean value and saving the state. Now update Board's`handleClick` function to flip the value of `xIsNext`.
```javascript
```javascript{3,6}
handleClick(i) {
const squares = this.state.squares.slice();
squares[i] = this.state.xIsNext ? 'X' : 'O';
@ -349,17 +532,102 @@ handleClick(i) {
Now X and O take turns. Next, change the "status" text in Board's `render` so that it also displays who is next.
[View the current code.](https://codepen.io/gaearon/pen/KmmrBy?editors=0010)
### Declaring a Winner
Let's show when the game is won. A `calculateWinner(squares)` helper function that takes the list of 9 values has been provided for you at the bottom of the file. You can call it in Board's `render` function to check if anyone has won the game and make the status text show "Winner: [X/O]" when someone wins:
Let's show when a game is won. Add this helper function to the end of the file:
You can now change `handleClick` to return early and ignore the click if someone has already won the game or if a square is already filled:
You can now change `handleClick`in Board to return early and ignore the click if someone has already won the game or if a square is already filled:
```javascript
```javascript{3-5}
handleClick(i) {
const squares = this.state.squares.slice();
if (calculateWinner(squares) || squares[i]) {
return;
}
// ...
squares[i] = this.state.xIsNext ? 'X' : 'O';
this.setState({
squares: squares,
xIsNext: !this.state.xIsNext,
});
}
```
Congratulations! You now have a working tic-tac-toe game. And now you know the basics of React. So *you're* probably the real winner here.
[View the current code.](https://codepen.io/gaearon/pen/LyyXgK?editors=0010)
## Storing a History
Let's make it possible to revisit old states of the board so we can see what it looked like after any of the previous moves. We're already creating a new `squares` array each time a move is made, which means we can easily store the past board states simultaneously.
@ -395,43 +670,102 @@ Let's plan to store an object like this in state:
```javascript
history = [
{
squares: [null x 9]
squares: [
null, null, null,
null, null, null,
null, null, null,
]
},
{
squares: [... x 9]
squares: [
null, null, null,
null, 'X', null,
null, null, null,
]
},
// ...
]
```
We'll want the top-level `Game` component to be responsible for displaying the list of moves. So just as we pulled the state up before from `Square` into `Board`, let's now pull it up again from `Board` into `Game` – so that we have all the information we need at the top level.
We'll want the top-level Game component to be responsible for displaying the list of moves. So just as we pulled the state up before from Square into Board, let's now pull it up again from Board into Game – so that we have all the information we need at the top level.
First, set up the initial state for `Game`:
First, set up the initial state for Game by adding a constructor to it:
```javascript
```javascript{2-10}
class Game extends React.Component {
constructor() {
super();
this.state = {
history: [{
squares: Array(9).fill(null)
squares: Array(9).fill(null),
}],
xIsNext: true
xIsNext: true,
};
}
// ...
render() {
return (
<divclassName="game">
<divclassName="game-board">
<Board/>
</div>
<divclassName="game-info">
<div>{/* status */}</div>
<ol>{/* TODO */}</ol>
</div>
</div>
);
}
}
```
Then remove the constructor from `Board` and change `Board` so that it takes `squares` via props and has its own `onClick` prop specified by `Game`, like the transformation we made for `Square` earlier. You can pass the location of each square into the click handler so that we still know which square was clicked:
Then change Board so that it takes `squares` via props and has its own `onClick` prop specified by Game, like the transformation we made for Square earlier. You can pass the location of each square into the click handler so that we still know which square was clicked. Here is a list of steps you need to do:
Since Game is now rendering the status, we can delete `<div className="status">{status}</div>` from the Board's `render` function.
Since Game is now rendering the status, we can delete `<div className="status">{status}</div>`and the code calculating the status from the Board's `render` function:
Game's `handleClick` can push a new entry onto the stack by concatenating the new history entry to make a new history array:
```js{1,2}
render() {
return (
<div>
<divclassName="board-row">
{this.renderSquare(0)}
{this.renderSquare(1)}
{this.renderSquare(2)}
</div>
<divclassName="board-row">
{this.renderSquare(3)}
{this.renderSquare(4)}
{this.renderSquare(5)}
</div>
<divclassName="board-row">
{this.renderSquare(6)}
{this.renderSquare(7)}
{this.renderSquare(8)}
</div>
</div>
);
}
```
```javascript
Next, we need to move the `handleClick` method implementation from Board to Game. You can cut it from the Board class, and paste it into the Game class.
We also need to change it a little, since Game state is structured differently. Game's `handleClick` can push a new entry onto the stack by concatenating the new history entry to make a new history array.
```javascript{2-4,10-12}
handleClick(i) {
const history = this.state.history;
const current = history[history.length - 1];
@ -481,11 +844,18 @@ handleClick(i) {
At this point, Board only needs `renderSquare` and `render`; the state initialization and click handler should both live in Game.
[View the current code.](https://codepen.io/gaearon/pen/EmmOqJ?editors=0010)
### Showing the Moves
Let's show the previous moves made in the game so far. We learned earlier that React elements are first-class JS objects and we can store them or pass them around. To render multiple items in React, we pass an array of React elements. The most common way to build that array is to map over your array of data. Let's do that in the `render` method of Game:
For each step in the history, we create a list item `<li>` with a link `<a>` inside it that goes nowhere (`href="#"`) but has a click handler which we'll implement shortly. With this code, you should see a list of the moves that have been made in the game, along with a warning that says
[View the current code.](https://codepen.io/gaearon/pen/EmmGEa?editors=0010)
For each step in the history, we create a list item `<li>` with a link `<a>` inside it that goes nowhere (`href="#"`) but has a click handler which we'll implement shortly. With this code, you should see a list of the moves that have been made in the game, along with a warning that says:
> Warning:
> Each child in an array or iterator should have a unique "key" prop. Check the render method of "Game".
@ -546,30 +937,102 @@ If you don't specify any key, React will warn you and fall back to using the arr
Component keys don't need to be globally unique, only unique relative to the immediate siblings.
### Implementing Time Travel
For our move list, we already have a unique ID for each step: the number of the move when it happened. Add the key as `<li key={move}>` and the key warning should disappear.
For our move list, we already have a unique ID for each step: the number of the move when it happened. In the Game's `render` method, add the key as `<li key={move}>` and the key warning should disappear:
Clicking any of the move links throws an error because `jumpTo` is undefined. Let's add a new key to Game's state to indicate which step we're currently viewing. First, add `stepNumber: 0` to the initial state, then have `jumpTo` update that state.
We also want to update `xIsNext`. We set `xIsNext` to true if the index of the move number is an even number.
[View the current code.](https://codepen.io/gaearon/pen/PmmXRE?editors=0010)
Clicking any of the move links throws an error because `jumpTo` is undefined. Let's add a new key to Game's state to indicate which step we're currently viewing.
First, add `stepNumber: 0` to the initial state in Game's `constructor`:
```js{8}
class Game extends React.Component {
constructor() {
super();
this.state = {
history: [{
squares: Array(9).fill(null),
}],
stepNumber: 0,
xIsNext: true,
};
}
```
Next, we'll define the `jumpTo` method in Game to update that state. We also want to update `xIsNext`. We set `xIsNext` to true if the index of the move number is an even number.
Add a method called `jumpTo` to the Game class:
```javascript{5-10}
handleClick(i) {
// this method has not changed
}
```javascript
jumpTo(step) {
this.setState({
stepNumber: step,
xIsNext: (step % 2) ? false : true,
});
}
render() {
// this method has not changed
}
```
Then update `stepNumber` when a new move is made by adding `stepNumber: history.length` to the state update in `handleClick`. Now you can modify `render` to read from that step in the history:
Then update `stepNumber` when a new move is made by adding `stepNumber: history.length` to the state update in Game's `handleClick`:
```javascript
```javascript{2,13}
handleClick(i) {
const history = this.state.history.slice(0, this.state.stepNumber + 1);
const current = history[history.length - 1];
const squares = current.squares.slice();
if (calculateWinner(squares) || squares[i]) {
return;
}
squares[i] = this.state.xIsNext ? 'X' : 'O';
this.setState({
history: history.concat([{
squares: squares
}]),
stepNumber: history.length,
xIsNext: !this.state.xIsNext,
});
}
```
Now you can modify Game's `render` to read from that step in the history:
```javascript{3}
render() {
const history = this.state.history;
const current = history[this.state.stepNumber];
const winner = calculateWinner(current.squares);
// the rest has not changed
```
If you click any move link now, the board should immediately update to show what the game looked like at that time. You may also want to update `handleClick` to be aware of `stepNumber` when reading the current board state so that you can go back in time then click in the board to create a new entry. (Hint: It's easiest to `.slice()` off the extra elements from `history` at the very top of `handleClick`.)
[View the current code.](https://codepen.io/gaearon/pen/gWWZgR?editors=0010)
If you click any move link now, the board should immediately update to show what the game looked like at that time.
You may also want to update `handleClick` to be aware of `stepNumber` when reading the current board state so that you can go back in time then click in the board to create a new entry. (Hint: It's easiest to `.slice()` off the extra elements from `history` at the very top of `handleClick`.)
### Wrapping Up
@ -582,6 +1045,8 @@ Now, you've made a tic-tac-toe game that:
Nice work! We hope you now feel like you have a decent grasp on how React works.
Check out the final result here: [Final Result](https://codepen.io/gaearon/pen/gWWZgR?editors=0010).
If you have extra time or want to practice your new skills, here are some ideas for improvements you could make, listed in order of increasing difficulty:
1. Display the move locations in the format "(1, 3)" instead of "6".
@ -589,3 +1054,5 @@ If you have extra time or want to practice your new skills, here are some ideas
3. Rewrite Board to use two loops to make the squares instead of hardcoding them.
4. Add a toggle button that lets you sort the moves in either ascending or descending order.
5. When someone wins, highlight the three squares that caused the win.
Throughout this tutorial, we have touched on a number of React concepts including elements, components, props, and state. For a more in-depth explanation for each of these topics, check out [the rest of the documentation](/react/docs/hello-world.html). To learn more about defining components, check out the [`React.Component` API reference](/react/docs/react-component.html).