React Tutorial の Wrapping Up の解答

https://reactjs.org/tutorial/tutorial.html
の最後にある Wrapping Up の自分なりの解答。
模範解答らしきものがなかったので上げておきます。

React初心者による解答です。ここをこうすればもっとうまくできるよ、みたいなのがあればご教示下さい。


###1.Display the location for each move in the format (col, row) in the move history list.

まずは、選ばれた場所を`Game`の`this.state.history`で管理します。

```javascript
class Game extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      history: [
        {
          squares: Array(9).fill(null),
          selected: null, // <---
        }
      ],
      stepNumber: 0,
      xIsNext: true
    };
  }
```
```javascript
  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,
          selected: i, // <---
        }
      ]),
      stepNumber: history.length,
      xIsNext: !this.state.xIsNext
    });
  }
```

そしたら、それを`(col, row)`の形にして`move`に追加してやりましょう。

```javascript
  render() {
    const history = this.state.history;
    const current = history[this.state.stepNumber];
    const winner = calculateWinner(current.squares);

    const moves = history.map((step, move) => {
      const desc = move ?
        'Go to move #' + move + ' (' + (step.selected % 3 + 1) + ', ' + (Math.floor(step.selected/3) + 1) + ')': // <---
        'Go to game start';
      return (
        <li key={move}>
          <button onClick={() => this.jumpTo(move)}>{desc}</button>
        </li>
      );
    });
```

###2. Bold the currently selected item in the move list.

ちょっと変えるだけです。

```javascript
  render() {
    const history = this.state.history;
    const current = history[this.state.stepNumber];
    const winner = calculateWinner(current.squares);

    const moves = history.map((step, move) => {
      let desc = move ? // <---
        'Go to move #' + move + ' (' + (step.selected % 3 + 1) + ', ' + (Math.floor(step.selected/3) + 1) + ')':
        'Go to game start';
      if (step === current) { // <---
        desc = <strong>{desc}</strong>;
      }
      return (
        <li key={move}>
          <button onClick={() => this.jumpTo(move)}>{desc}</button>
        </li>
      );
    });
```

###3. Rewrite Board to use two loops to make the squares instead of hardcoding them.

Reactのループ処理は少しコツが要りますね(僕だけでしょうか)。`key`も忘れずにつけてやりましょう。

```javascript
class Board extends React.Component {
  renderSquare(i) {
    return (
      <Square
        key={i} // <---
        value={this.props.squares[i]}
        onClick={() => this.props.onClick(i)}
      />
    );
  }

  render() {
    // ↓↓
    const rows = Array(3);
    for (let i of [0, 1, 2]) {
      const items = Array(3);
      for (let j of [0, 1, 2]) {
        const index = i*3 + j;
        items[j] = this.renderSquare(index);
      }
      rows[i] = (
        <div key={i} className="board-row">
          {items}
        </div>
      );
    }
    return (
      <div>{rows}</div>
    );
    // ↑↑
  }
}
```

###4. Add a toggle button that lets you sort the moves in either ascending or descending order.

`moves`が`ascending`かどうかを、`Game`の`this.state.movesIsAsc`で管理します。初期状態は`true`ですね。

```javascript
class Game extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      history: [
        {
          squares: Array(9).fill(null),
          selected: null, 
        }
      ],
      stepNumber: 0,
      xIsNext: true,
      movesIsAsc: true, // <---
    };
  }
```

次に、これの`true` `false`を切り替えるメソッドを作ります。

```javascript
  jumpTo(step) {
    this.setState({
      stepNumber: step,
      xIsNext: (step % 2) === 0
    });
  }
  // ↓↓
  sortMovesReverse() { // このメソッド名が正しい英語かは知らない
    this.setState({
      movesIsAsc: !this.state.movesIsAsc,
    });
  }
  // ↑↑
  render() {
    const history = this.state.history;
    const current = history[this.state.stepNumber];
    const winner = calculateWinner(current.squares);
```

そしたら、最後にこれを反映させていきましょう。

```javascript
    return (
      <div className="game">
        <div className="game-board">
          <Board
            squares={current.squares}
            onClick={i => this.handleClick(i)}
          />
        </div>
        <div className="game-info">
          <div>{status}</div>
          // ↓↓
          <div><button onClick={() => this.sortMovesReverse()}>
            {this.state.movesIsAsc ? 'Sort descending' : 'Sort ascending'}
          </button></div>
          {this.state.movesIsAsc ? <ol>{moves}</ol> : <ol reverse>{moves.reverse()}</ol>}
          // ↑↑
        </div>
      </div>
    );
```

変数で置いた方がすっきりしそうですね(面倒くさい)。

###5. When someone wins, highlight the three squares that caused the win.

`calculateWinner`関数を改造して`line`も返すようにしてやりましょう。それに合わせて他の部分も修正します。

```javascript
function calculateWinner(squares) {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6]
  ];
  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      // ↓↓
      return {
        winner: squares[a],
        line: lines[i],
      };
      // ↑↑
    }
  }
  // ↓↓
  return {
    winner: null,
    line: null,
  };
  // ↑↑
}
```

```javascript
  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).winner || squares[i]) { // <---
      return;
    }
    squares[i] = this.state.xIsNext ? "X" : "O";
    this.setState({
      history: history.concat([
```

```javascript
  render() {
    const history = this.state.history;
    const current = history[this.state.stepNumber];
    const calcResult = calculateWinner(current.squares); // <---

    const moves = history.map((step, move) => {
      let desc = move ?
        'Go to move #' + move + ' (' + (step.selected % 3 + 1) + ', ' + (Math.floor(step.selected/3) + 1) + ')':
        'Go to game start';
      if (step === current) {
        desc = <strong>{desc}</strong>;
      }
      return (
        <li key={move}>
          <button onClick={() => this.jumpTo(move)}>{desc}</button>
        </li>
      );
    });

    let status;
    if (calcResult.winner) { // <---
      status = "Winner: " + calcResult.winner; // <---
    } else {
      status = "Next player: " + (this.state.xIsNext ? "X" : "O");
    }
```

そして、`Board`に`line`を渡します。

```javascript
    return (
      <div className="game">
        <div className="game-board">
          <Board
            squares={current.squares}
            onClick={i => this.handleClick(i)}
            winLine={calcResult.line} // <---
          />
        </div>
```

そして、該当する`Square`をハイライトします。

```javascript
class Board extends React.Component {
  renderSquare(i, isHighlighted) { // <---
    return (
      <Square
        key={i}
        value={this.props.squares[i]}
        onClick={() => this.props.onClick(i)}
        isHighlighted={isHighlighted} // <---
      />
    );
  }

  render() {
    const rows = Array(3);
    for (let i of [0, 1, 2]) {
      const items = Array(3);
      for (let j of [0, 1, 2]) {
        const index = i*3 + j;
        // ↓↓
        const highlight = this.props.winLine && this.props.winLine.includes(index);
        items[j] = this.renderSquare(index, highlight);
        // ↑↑
      }
```

```javascript
function Square(props) {
  // ↓↓
  let className = 'square';
  if (props.isHighlighted) {
    className += ' highlighted';
  }
  // ↑↑
  return (
    <button className={className} onClick={props.onClick}> // <---
      {props.value}
    </button>
  );
}
```

```css:css
.square.highlighted {
  background-color: dodgerblue;
}
```

###6. When no one wins, display a message about the result being a draw.

また、`calculateWinner`関数を改造しましょう。

```javascript
    [0, 4, 8],
    [2, 4, 6]
  ];
  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      return {
        winner: squares[a],
        line: lines[i],
      };
    }
  }
  // ↓↓
  if (squares.every(s => s)) {
    return {
      winner: 'DRAW',
      line: null,
    };
  }
  // ↑↑
  return {
    winner: null,
    line: null,
  };
}
```

```javascript
      return (
        <li key={move}>
          <button onClick={() => this.jumpTo(move)}>{desc}</button>
        </li>
      );
    });

    let status;
    // ↓↓
    if (calcResult.winner && calcResult.winner !== 'DRAW') {
      status = "Winner: " + calcResult.winner;
    } else if (calcResult.winner === 'DRAW') {
      status = "DRAW...";
    // ↑↑
    } else {
      status = "Next player: " + (this.state.xIsNext ? "X" : "O");
    }

    return (
      <div className="game">
        <div className="game-board">
          <Board
```