@samitouri / QOS-React-2 / commits / e9d6f3f10e

[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

Frankie Bagnardi committed May 1, 2017 at 09:22 UTC e9d6f3f10e825222182ffc38c003ac1e3a6f1598
2 files changed +635 -171
docs/Gemfile.lock
-3
@@ -65,6 +65,3 @@ DEPENDENCIES
65 rb-fsevent
66 redcarpet
67 sanitize (~> 2.0)
68 -
69 -BUNDLED WITH
70 - 1.11.2
docs/tutorial/tutorial.md
+635 -168
@@ -18,7 +18,7 @@ redirect_from:
18
19 Today, we're going to build an interactive tic-tac-toe game.
20
21 -If you like, you can check out the final result here: <a href="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.
21 +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.
22
23 ### Prerequisites
24
@@ -30,17 +30,19 @@ If you need a refresher on JavaScript, we recommend reading [this guide](https:/
30
31 #### Following Along in Browser
32
33 -We'll be using an online editor called CodePen in this guide. You can begin by opening this <a href="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.
33 +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.
34
35 #### Following Along Locally
36
37 -You can also follow along locally if you don't mind a few extra steps:
37 +Alternatively, you can set up a project on your computer.
38 +
39 +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).
40
41 1. Make sure you have a recent version of [Node.js](https://nodejs.org/en/) installed.
42 2. Follow the [installation instructions](/react/docs/installation.html#creating-a-new-application) to create a new project.
43 3. Delete all files in the `src/` folder of the new project.
42 -4. Add a file named `index.css` in the `src/` folder with <a href="https://codepen.io/gaearon/pen/JNYBEZ?editors=0100" target="_blank">this CSS code</a>.
43 -5. Add a file named `index.js` in the `src/` folder with <a href="https://codepen.io/gaearon/pen/JNYBEZ?editors=0010" target="_blank">this JS code</a>, and then add three lines to the top of it:
44 +4. Add a file named `index.css` in the `src/` folder with [this CSS code](https://codepen.io/gaearon/pen/oWWQNa?editors=0100).
45 +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:
46
47 ```js
48 import React from 'react';
@@ -54,7 +56,7 @@ Now if you run `npm start` in the project folder and open `http://localhost:3000
56
57 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.
58
57 -You can also look at the <a href="https://codepen.io/gaearon/pen/VbvBWg?editors=0010" target="_blank">final version of the code</a>.
59 +You can also look at the [final version of the code](https://codepen.io/gaearon/pen/gWWZgR?editors=0010).
60
61 With this out of the way, let's get started!
62
@@ -98,6 +100,8 @@ return React.createElement('div', {className: 'shopping-list'},
100 );
101 ```
102
103 +[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)
104 +
105 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.
106
107 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
110
111 ### Getting Started
112
109 -Start with this example: <a href="https://codepen.io/gaearon/pen/JNYBEZ?editors=0010" target="_blank">Starter Code</a>.
113 +Start with this example: [Starter Code](https://codepen.io/gaearon/pen/oWWQNa?editors=0010).
114
115 It contains the shell of what we're building today. We've provided the styles so you only need to worry about the JavaScript.
116
@@ -118,11 +122,32 @@ In particular, we have three components:
122
123 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.
124
121 -(The end of the JS file also defines a helper function `calculateWinner` that we'll use later.)
122 -
125 ### Passing Data Through Props
126
125 -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}`.
127 +Just to get our feet wet, let's try passing some data from the Board component to the Square component.
128 +
129 +In Board's `renderSquare` method, change the code to pass a `value` prop to the Square:
130 +
131 +```js{3}
132 +class Board extends React.Component {
133 + renderSquare(i) {
134 + return <Square value={i} />;
135 + }
136 +```
137 +
138 +Then change Square's `render` method to show that value by replacing `{/* TODO */}` with `{this.props.value}`:
139 +
140 +```js{5}
141 +class Square extends React.Component {
142 + render() {
143 + return (
144 + <button className="square">
145 + {this.props.value}
146 + </button>
147 + );
148 + }
149 +}
150 +```
151
152 Before:
153
@@ -132,21 +157,33 @@ After: You should see a number in each square in the rendered output.
157
158 ![React Devtools](/react/img/tutorial/tictac-numbers.png)
159
160 +[View the current code.](https://codepen.io/gaearon/pen/aWWQOG?editors=0010)
161 +
162 ### An Interactive Component
163
137 -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:
164 +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:
165
139 -```html
140 -<button className="square" onClick={() => alert('click')}>
141 - {/* TODO */}
142 -</button>
166 +```javascript{4}
167 +class Square extends React.Component {
168 + render() {
169 + return (
170 + <button className="square" onClick={() => alert('click')}>
171 + {this.props.value}
172 + </button>
173 + );
174 + }
175 +}
176 ```
177
145 -This uses the new JavaScript arrow function syntax. If you click on a square now, you should get an alert in your browser.
178 +If you click on a square now, you should get an alert in your browser.
179
147 -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:
180 +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.
181
149 -```javascript
182 +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.
183 +
184 +First, add a constructor to the class to initialize the state:
185 +
186 +```javascript{2-7}
187 class Square extends React.Component {
188 constructor() {
189 super();
@@ -154,24 +191,51 @@ class Square extends React.Component {
191 value: null,
192 };
193 }
157 - // ...
194 +
195 + render() {
196 + return (
197 + <button className="square" onClick={() => alert('click')}>
198 + {this.props.value}
199 + </button>
200 + );
201 + }
202 }
203 ```
204
161 -In JavaScript classes, you need to explicitly call `super();` when defining the constructor of a subclass.
205 +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.
206
163 -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:
207 +Now change the Square `render` method to display the value from the current state, and to toggle it on click:
208
165 -```javascript
166 -<button className="square" onClick={() => this.setState({value: 'X'})}>
167 - {this.state.value}
168 -</button>
209 +* Replace `this.props.value` with `this.state.value` inside the `<button>` tag.
210 +* Replace the `() => alert()` event handler with `() => setState({value: 'X'})`.
211 +
212 +Now the `<button>` tag looks like this:
213 +
214 +```javascript{10-12}
215 +class Square extends React.Component {
216 + constructor() {
217 + super();
218 + this.state = {
219 + value: null,
220 + };
221 + }
222 +
223 + render() {
224 + return (
225 + <button className="square" onClick={() => this.setState({value: 'X'})}>
226 + {this.state.value}
227 + </button>
228 + );
229 + }
230 +}
231 ```
232
233 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.
234
235 If you click on any square, an X should show up in it.
236
237 +[View the current code.](https://codepen.io/gaearon/pen/VbbVLg?editors=0010)
238 +
239 ### Developer Tools
240
241 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
244
245 It lets you inspect the props and state of any of the components in your tree.
246
183 -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.
247 +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:
248 +
249 +1. Log in or register and confirm your email (required to prevent spam).
250 +2. Click the "Fork" button.
251 +3. Click "Change View" and then choose "Debug mode".
252 +4. In the new tab that opens, the devtools should now have a React tab.
253
254 ## Lifting State Up
255
@@ -192,9 +261,9 @@ Instead, the best solution here is to store this state in the Board component in
261
262 **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.**
263
195 -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:
264 +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:
265
197 -```javascript
266 +```javascript{2-7}
267 class Board extends React.Component {
268 constructor() {
269 super();
@@ -202,6 +271,33 @@ class Board extends React.Component {
271 squares: Array(9).fill(null),
272 };
273 }
274 +
275 + renderSquare(i) {
276 + return <Square value={i} />;
277 + }
278 +
279 + render() {
280 + return (
281 + <div>
282 + <div className="status">{status}</div>
283 + <div className="board-row">
284 + {this.renderSquare(0)}
285 + {this.renderSquare(1)}
286 + {this.renderSquare(2)}
287 + </div>
288 + <div className="board-row">
289 + {this.renderSquare(3)}
290 + {this.renderSquare(4)}
291 + {this.renderSquare(5)}
292 + </div>
293 + <div className="board-row">
294 + {this.renderSquare(6)}
295 + {this.renderSquare(7)}
296 + {this.renderSquare(8)}
297 + </div>
298 + </div>
299 + );
300 + }
301 }
302 ```
303
@@ -215,26 +311,59 @@ We'll fill it in later so that a board looks something like
311 ]
312 ```
313
218 -Pass the value of each square down:
314 +Board's `renderSquare` method currently looks like this:
315
316 ```javascript
221 -renderSquare(i) {
222 - return <Square value={this.state.squares[i]} />;
223 -}
317 + renderSquare(i) {
318 + return <Square value={i} />;
319 + }
320 ```
321
226 -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:
322 +Modify it to pass a `value` prop to Square.
323
228 -```javascript
229 -return <Square value={this.state.squares[i]} onClick={() => this.handleClick(i)} />;
324 +```javascript{2}
325 + renderSquare(i) {
326 + return <Square value={this.state.squares[i]} />;
327 + }
328 ```
329
232 -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()`:
330 +[View the current code.](https://codepen.io/gaearon/pen/gWWQPY?editors=0010)
331
234 -```javascript
235 -<button className="square" onClick={() => this.props.onClick()}>
236 - {this.props.value}
237 -</button>
332 +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.
333 +
334 +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:
335 +
336 +```javascript{5}
337 + renderSquare(i) {
338 + return (
339 + <Square
340 + value={this.state.squares[i]}
341 + onClick={() => this.handleClick(i)}
342 + />
343 + );
344 + }
345 +```
346 +
347 +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.
348 +
349 +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:
350 +
351 +* Replace `this.state.value` with `this.props.value` in Square's `render`.
352 +* Replace `this.setState()` with `this.props.onClick()` in Square's `render`.
353 +* Delete `constructor` definition from Square because it doesn't have state anymore.
354 +
355 +After these changes, the whole Square component looks like this:
356 +
357 +```javascript{1,2,4,5}
358 +class Square extends React.Component {
359 + render() {
360 + return (
361 + <button className="square" onClick={() => this.props.onClick()}>
362 + {this.props.value}
363 + </button>
364 + );
365 + }
366 +}
367 ```
368
369 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
371 1. The `onClick` prop on the built-in DOM `<button>` component tells React to set up a click event listener.
372 2. When the button is clicked, React will call the `onClick` event handler defined in Square's `render()` method.
373 3. This event handler calls `this.props.onClick()`. Square's props were specified by the Board.
245 -4. This is how we get into `onClick` passed from the Board, which runs `this.handleClick()` on the Board.
246 -5. We have not defined `this.handleClick` on the Board yet, so the code crashes.
374 +4. Board passed `onClick={() => this.handleClick(i)}` to Square, so, when called, it runs `this.handleClick(i)` on the Board.
375 +5. We have not defined the `handleClick()` method on the Board yet, so the code crashes.
376
377 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.
378
250 -Try clicking a square – you should get an error because we haven't defined `handleClick` yet. Add it to the Board class:
379 +Try clicking a square – you should get an error because we haven't defined `handleClick` yet. Add it to the Board class.
380
252 -```javascript
253 -handleClick(i) {
254 - const squares = this.state.squares.slice();
255 - squares[i] = 'X';
256 - this.setState({squares: squares});
381 +```javascript{9-13}
382 +class Board extends React.Component {
383 + constructor() {
384 + super();
385 + this.state = {
386 + squares: Array(9).fill(null),
387 + };
388 + }
389 +
390 + handleClick(i) {
391 + const squares = this.state.squares.slice();
392 + squares[i] = 'X';
393 + this.setState({squares: squares});
394 + }
395 +
396 + renderSquare(i) {
397 + return (
398 + <Square
399 + value={this.state.squares[i]}
400 + onClick={() => this.handleClick(i)}
401 + />
402 + );
403 + }
404 +
405 + render() {
406 + const status = 'Next player: X';
407 + return (
408 + <div>
409 + <div className="status">{status}</div>
410 + <div className="board-row">
411 + {this.renderSquare(0)}
412 + {this.renderSquare(1)}
413 + {this.renderSquare(2)}
414 + </div>
415 + <div className="board-row">
416 + {this.renderSquare(3)}
417 + {this.renderSquare(4)}
418 + {this.renderSquare(5)}
419 + </div>
420 + <div className="board-row">
421 + {this.renderSquare(6)}
422 + {this.renderSquare(7)}
423 + {this.renderSquare(8)}
424 + </div>
425 + </div>
426 + );
427 + }
428 }
429 ```
430
431 +[View the current code.](https://codepen.io/gaearon/pen/ybbQJX?editors=0010)
432 +
433 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.
434
435 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.
436
264 -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**.
437 +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**.
438
439 ### Why Immutability Is Important
440
@@ -289,26 +462,32 @@ var newPlayer = Object.assign({}, player, {score: 2});
462
463 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.
464
465 +#### Easier Undo/Redo and Time Travel
466 +
467 +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.
468 +
469 #### Tracking Changes
470
471 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.
472
473 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.
474
298 -#### Determining When To Re-render in React
475 +#### Determining When to Re-render in React
476
477 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.
478
302 -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.
479 +To learn more about `shouldComponentUpdate()` and how you can build *pure components* take a look at [Optimizing Performance](/react/docs/optimizing-performance.html#examples).
480
481 ### Functional Components
482
306 -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:
483 +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.
484 +
485 +Replace the whole Square class with this function:
486
487 ```javascript
488 function Square(props) {
489 return (
311 - <button className="square" onClick={() => props.onClick()}>
490 + <button className="square" onClick={props.onClick}>
491 {props.value}
492 </button>
493 );
@@ -317,75 +496,171 @@ function Square(props) {
496
497 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.
498
499 +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.
500 +
501 +[View the current code.](https://codepen.io/gaearon/pen/QvvJOv?editors=0010)
502 +
503 ### Taking Turns
504
505 An obvious defect in our game is that only X can play. Let's fix that.
506
324 -Let's default the first move to be by 'X'. Modify our starting state in our `Board` constructor.
507 +Let's default the first move to be by 'X'. Modify our starting state in our Board constructor.
508
326 -```javascript
509 +```javascript{6}
510 class Board extends React.Component {
511 constructor() {
512 super();
513 this.state = {
331 - // ...
514 + squares: Array(9).fill(null),
515 xIsNext: true,
516 };
517 }
518 ```
519
337 -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`.
520 +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`.
521
339 -```javascript
340 -handleClick(i) {
341 - const squares = this.state.squares.slice();
342 - squares[i] = this.state.xIsNext ? 'X' : 'O';
343 - this.setState({
344 - squares: squares,
345 - xIsNext: !this.state.xIsNext,
346 - });
347 -}
522 +```javascript{3,6}
523 + handleClick(i) {
524 + const squares = this.state.squares.slice();
525 + squares[i] = this.state.xIsNext ? 'X' : 'O';
526 + this.setState({
527 + squares: squares,
528 + xIsNext: !this.state.xIsNext,
529 + });
530 + }
531 ```
532
533 Now X and O take turns. Next, change the "status" text in Board's `render` so that it also displays who is next.
534
352 -```javascript
353 -render() {
354 - const status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
355 - // ...
535 +```javascript{2}
536 + render() {
537 + const status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
538 +
539 + return (
540 + // the rest has not changed
541 ```
542
358 -### Declaring a Winner
543 +After these changes you should have this Board component:
544
360 -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:
545 +```javascript{6,11-16,29}
546 +class Board extends React.Component {
547 + constructor() {
548 + super();
549 + this.state = {
550 + squares: Array(9).fill(null),
551 + xIsNext: true,
552 + };
553 + }
554
362 -```javascript
363 -render() {
364 - const winner = calculateWinner(this.state.squares);
365 - let status;
366 - if (winner) {
367 - status = 'Winner: ' + winner;
368 - } else {
369 - status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
555 + handleClick(i) {
556 + const squares = this.state.squares.slice();
557 + squares[i] = this.state.xIsNext ? 'X' : 'O';
558 + this.setState({
559 + squares: squares,
560 + xIsNext: !this.state.xIsNext,
561 + });
562 + }
563 +
564 + renderSquare(i) {
565 + return (
566 + <Square
567 + value={this.state.squares[i]}
568 + onClick={() => this.handleClick(i)}
569 + />
570 + );
571 + }
572 +
573 + render() {
574 + const status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
575 +
576 + return (
577 + <div>
578 + <div className="status">{status}</div>
579 + <div className="board-row">
580 + {this.renderSquare(0)}
581 + {this.renderSquare(1)}
582 + {this.renderSquare(2)}
583 + </div>
584 + <div className="board-row">
585 + {this.renderSquare(3)}
586 + {this.renderSquare(4)}
587 + {this.renderSquare(5)}
588 + </div>
589 + <div className="board-row">
590 + {this.renderSquare(6)}
591 + {this.renderSquare(7)}
592 + {this.renderSquare(8)}
593 + </div>
594 + </div>
595 + : );
596 }
371 - // ...
597 }
598 ```
599
375 -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:
600 +[View the current code.](https://codepen.io/gaearon/pen/KmmrBy?editors=0010)
601 +
602 +### Declaring a Winner
603 +
604 +Let's show when a game is won. Add this helper function to the end of the file:
605
606 ```javascript
378 -handleClick(i) {
379 - const squares = this.state.squares.slice();
380 - if (calculateWinner(squares) || squares[i]) {
381 - return;
607 +function calculateWinner(squares) {
608 + const lines = [
609 + [0, 1, 2],
610 + [3, 4, 5],
611 + [6, 7, 8],
612 + [0, 3, 6],
613 + [1, 4, 7],
614 + [2, 5, 8],
615 + [0, 4, 8],
616 + [2, 4, 6],
617 + ];
618 + for (let i = 0; i < lines.length; i++) {
619 + const [a, b, c] = lines[i];
620 + if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
621 + return squares[a];
622 + }
623 }
383 - // ...
624 + return null;
625 }
626 ```
627
628 +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:
629 +
630 +```javascript{2-8}
631 + render() {
632 + const winner = calculateWinner(this.state.squares);
633 + let status;
634 + if (winner) {
635 + status = 'Winner: ' + winner;
636 + } else {
637 + status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
638 + }
639 +
640 + return (
641 + // the rest has not changed
642 +```
643 +
644 +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:
645 +
646 +```javascript{3-5}
647 + handleClick(i) {
648 + const squares = this.state.squares.slice();
649 + if (calculateWinner(squares) || squares[i]) {
650 + return;
651 + }
652 + squares[i] = this.state.xIsNext ? 'X' : 'O';
653 + this.setState({
654 + squares: squares,
655 + xIsNext: !this.state.xIsNext,
656 + });
657 + }
658 +```
659 +
660 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.
661
662 +[View the current code.](https://codepen.io/gaearon/pen/LyyXgK?editors=0010)
663 +
664 ## Storing a History
665
666 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,114 +670,230 @@ Let's plan to store an object like this in state:
670 ```javascript
671 history = [
672 {
398 - squares: [null x 9]
673 + squares: [
674 + null, null, null,
675 + null, null, null,
676 + null, null, null,
677 + ]
678 },
679 {
401 - squares: [... x 9]
680 + squares: [
681 + null, null, null,
682 + null, 'X', null,
683 + null, null, null,
684 + ]
685 },
686 // ...
687 ]
688 ```
689
407 -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.
690 +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.
691
409 -First, set up the initial state for `Game`:
692 +First, set up the initial state for Game by adding a constructor to it:
693
411 -```javascript
694 +```javascript{2-10}
695 class Game extends React.Component {
696 constructor() {
697 super();
698 this.state = {
699 history: [{
417 - squares: Array(9).fill(null)
700 + squares: Array(9).fill(null),
701 }],
419 - xIsNext: true
702 + xIsNext: true,
703 };
704 }
422 - // ...
705 +
706 + render() {
707 + return (
708 + <div className="game">
709 + <div className="game-board">
710 + <Board />
711 + </div>
712 + <div className="game-info">
713 + <div>{/* status */}</div>
714 + <ol>{/* TODO */}</ol>
715 + </div>
716 + </div>
717 + );
718 + }
719 }
720 ```
721
426 -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:
722 +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:
723
428 -```javascript
429 -return <Square value={this.props.squares[i]} onClick={() => this.props.onClick(i)} />;
430 -```
724 +* Delete the `constructor` in Board.
725 +* Replace `this.state.squares[i]` with `this.props.squares[i]` in Board's `renderSquare`.
726 +* Replace `this.handleClick(i)` with `this.props.onClick(i)` in Board's `renderSquare`.
727
432 -`Game`'s `render` should look at the most recent history entry and can take over calculating the game status:
728 +Now the whole Board component looks like this:
729
434 -```javascript
435 -const history = this.state.history;
436 -const current = history[history.length - 1];
437 -const winner = calculateWinner(current.squares);
438 -
439 -let status;
440 -if (winner) {
441 - status = 'Winner: ' + winner;
442 -} else {
443 - status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
730 +```javascript{1,2,5,6}
731 +class Board extends React.Component {
732 + renderSquare(i) {
733 + return (
734 + <Square
735 + value={this.props.squares[i]}
736 + onClick={() => this.props.onClick(i)}
737 + />
738 + );
739 + }
740 +
741 + render() {
742 + return (
743 + <div>
744 + <div className="board-row">
745 + {this.renderSquare(0)}
746 + {this.renderSquare(1)}
747 + {this.renderSquare(2)}
748 + </div>
749 + <div className="board-row">
750 + {this.renderSquare(3)}
751 + {this.renderSquare(4)}
752 + {this.renderSquare(5)}
753 + </div>
754 + <div className="board-row">
755 + {this.renderSquare(6)}
756 + {this.renderSquare(7)}
757 + {this.renderSquare(8)}
758 + </div>
759 + </div>
760 + );
761 + }
762 }
763 +```
764 +
765 +Game's `render` should look at the most recent history entry and can take over calculating the game status:
766
446 -// ...
767 +```javascript{2-11,16-19,22}
768 + render() {
769 + const history = this.state.history;
770 + const current = history[history.length - 1];
771 + const winner = calculateWinner(current.squares);
772
448 -<div className="game-board">
449 - <Board
450 - squares={current.squares}
451 - onClick={(i) => this.handleClick(i)}
452 - />
453 -</div>
454 -<div className="game-info">
455 - <div>{status}</div>
456 - <ol>{/* TODO */}</ol>
457 -</div>
773 + let status;
774 + if (winner) {
775 + status = 'Winner: ' + winner;
776 + } else {
777 + status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
778 + }
779 +
780 + return (
781 + <div className="game">
782 + <div className="game-board">
783 + <Board
784 + squares={current.squares}
785 + onClick={(i) => this.handleClick(i)}
786 + />
787 + </div>
788 + <div className="game-info">
789 + <div>{status}</div>
790 + <ol>{/* TODO */}</ol>
791 + </div>
792 + </div>
793 + );
794 + }
795 ```
796
460 -Since Game is now rendering the status, we can delete `<div className="status">{status}</div>` from the Board's `render` function.
797 +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:
798
462 -Game's `handleClick` can push a new entry onto the stack by concatenating the new history entry to make a new history array:
799 +```js{1,2}
800 + render() {
801 + return (
802 + <div>
803 + <div className="board-row">
804 + {this.renderSquare(0)}
805 + {this.renderSquare(1)}
806 + {this.renderSquare(2)}
807 + </div>
808 + <div className="board-row">
809 + {this.renderSquare(3)}
810 + {this.renderSquare(4)}
811 + {this.renderSquare(5)}
812 + </div>
813 + <div className="board-row">
814 + {this.renderSquare(6)}
815 + {this.renderSquare(7)}
816 + {this.renderSquare(8)}
817 + </div>
818 + </div>
819 + );
820 + }
821 +```
822
464 -```javascript
465 -handleClick(i) {
466 - const history = this.state.history;
467 - const current = history[history.length - 1];
468 - const squares = current.squares.slice();
469 - if (calculateWinner(squares) || squares[i]) {
470 - return;
471 - }
472 - squares[i] = this.state.xIsNext ? 'X' : 'O';
473 - this.setState({
474 - history: history.concat([{
475 - squares: squares
476 - }]),
477 - xIsNext: !this.state.xIsNext,
478 - });
479 -}
823 +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.
824 +
825 +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.
826 +
827 +```javascript{2-4,10-12}
828 + handleClick(i) {
829 + const history = this.state.history;
830 + const current = history[history.length - 1];
831 + const squares = current.squares.slice();
832 + if (calculateWinner(squares) || squares[i]) {
833 + return;
834 + }
835 + squares[i] = this.state.xIsNext ? 'X' : 'O';
836 + this.setState({
837 + history: history.concat([{
838 + squares: squares
839 + }]),
840 + xIsNext: !this.state.xIsNext,
841 + });
842 + }
843 ```
844
845 At this point, Board only needs `renderSquare` and `render`; the state initialization and click handler should both live in Game.
846
847 +[View the current code.](https://codepen.io/gaearon/pen/EmmOqJ?editors=0010)
848 +
849 ### Showing the Moves
850
851 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:
852
488 -```javascript
489 -const moves = history.map((step, move) => {
490 - const desc = move ?
491 - 'Move #' + move :
492 - 'Game start';
493 - return (
494 - <li>
495 - <a href="#" onClick={() => this.jumpTo(move)}>{desc}</a>
496 - </li>
497 - );
498 -});
499 -
500 -// ...
853 +```javascript{6-15,34}
854 + render() {
855 + const history = this.state.history;
856 + const current = history[history.length - 1];
857 + const winner = calculateWinner(current.squares);
858 +
859 + const moves = history.map((step, move) => {
860 + const desc = move ?
861 + 'Move #' + move :
862 + 'Game start';
863 + return (
864 + <li>
865 + <a href="#" onClick={() => this.jumpTo(move)}>{desc}</a>
866 + </li>
867 + );
868 + });
869 +
870 + let status;
871 + if (winner) {
872 + status = 'Winner: ' + winner;
873 + } else {
874 + status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
875 + }
876
502 -<ol>{moves}</ol>
877 + return (
878 + <div className="game">
879 + <div className="game-board">
880 + <Board
881 + squares={current.squares}
882 + onClick={(i) => this.handleClick(i)}
883 + />
884 + </div>
885 + <div className="game-info">
886 + <div>{status}</div>
887 + <ol>{moves}</ol>
888 + </div>
889 + </div>
890 + );
891 + }
892 ```
893
505 -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
894 +[View the current code.](https://codepen.io/gaearon/pen/EmmGEa?editors=0010)
895 +
896 +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:
897
898 > Warning:
899 > 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
937
938 Component keys don't need to be globally unique, only unique relative to the immediate siblings.
939
940 +
941 ### Implementing Time Travel
942
551 -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.
943 +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:
944 +
945 +```js{6}
946 + const moves = history.map((step, move) => {
947 + const desc = move ?
948 + 'Move #' + move :
949 + 'Game start';
950 + return (
951 + <li key={move}>
952 + <a href="#" onClick={() => this.jumpTo(move)}>{desc}</a>
953 + </li>
954 + );
955 + });
956 +```
957
553 -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.
958 +[View the current code.](https://codepen.io/gaearon/pen/PmmXRE?editors=0010)
959
555 -We also want to update `xIsNext`. We set `xIsNext` to true if the index of the move number is an even number.
960 +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.
961
557 -```javascript
558 -jumpTo(step) {
559 - this.setState({
560 - stepNumber: step,
561 - xIsNext: (step % 2) ? false : true,
562 - });
563 -}
962 +First, add `stepNumber: 0` to the initial state in Game's `constructor`:
963 +
964 +```js{8}
965 +class Game extends React.Component {
966 + constructor() {
967 + super();
968 + this.state = {
969 + history: [{
970 + squares: Array(9).fill(null),
971 + }],
972 + stepNumber: 0,
973 + xIsNext: true,
974 + };
975 + }
976 ```
977
566 -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:
978 +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.
979
568 -```javascript
569 -const current = history[this.state.stepNumber];
980 +Add a method called `jumpTo` to the Game class:
981 +
982 +```javascript{5-10}
983 + handleClick(i) {
984 + // this method has not changed
985 + }
986 +
987 + jumpTo(step) {
988 + this.setState({
989 + stepNumber: step,
990 + xIsNext: (step % 2) ? false : true,
991 + });
992 + }
993 +
994 + render() {
995 + // this method has not changed
996 + }
997 +```
998 +
999 +Then update `stepNumber` when a new move is made by adding `stepNumber: history.length` to the state update in Game's `handleClick`:
1000 +
1001 +```javascript{2,13}
1002 + handleClick(i) {
1003 + const history = this.state.history.slice(0, this.state.stepNumber + 1);
1004 + const current = history[history.length - 1];
1005 + const squares = current.squares.slice();
1006 + if (calculateWinner(squares) || squares[i]) {
1007 + return;
1008 + }
1009 + squares[i] = this.state.xIsNext ? 'X' : 'O';
1010 + this.setState({
1011 + history: history.concat([{
1012 + squares: squares
1013 + }]),
1014 + stepNumber: history.length,
1015 + xIsNext: !this.state.xIsNext,
1016 + });
1017 + }
1018 +```
1019 +
1020 +Now you can modify Game's `render` to read from that step in the history:
1021 +
1022 +```javascript{3}
1023 + render() {
1024 + const history = this.state.history;
1025 + const current = history[this.state.stepNumber];
1026 + const winner = calculateWinner(current.squares);
1027 +
1028 + // the rest has not changed
1029 ```
1030
572 -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`.)
1031 +[View the current code.](https://codepen.io/gaearon/pen/gWWZgR?editors=0010)
1032 +
1033 +If you click any move link now, the board should immediately update to show what the game looked like at that time.
1034 +
1035 +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`.)
1036
1037 ### Wrapping Up
1038
@@ -582,6 +1045,8 @@ Now, you've made a tic-tac-toe game that:
1045
1046 Nice work! We hope you now feel like you have a decent grasp on how React works.
1047
1048 +Check out the final result here: [Final Result](https://codepen.io/gaearon/pen/gWWZgR?editors=0010).
1049 +
1050 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:
1051
1052 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
1054 3. Rewrite Board to use two loops to make the squares instead of hardcoding them.
1055 4. Add a toggle button that lets you sort the moves in either ascending or descending order.
1056 5. When someone wins, highlight the three squares that caused the win.
1057 +
1058 +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).