0

Working on the react.js tic-tac-toe tutorial trying to add row, col information to the list of game moves. I added a method that determines the row and column of the current move, so that I can output something like Go to move #1 (row#,col#) in the list of previous moves. The method returns a string value that I want to use in the <li><button>{desc}.

But when I call the method on each click of the Game board, instead of updating only the current <li><button>, all of the <li> elements are updated with the most recent row, col information. I thought I could fix this by adding row, col to the <li> key attribute, but it still happens. what am i missing? thanks

Codepen: https://codepen.io/anon/pen/qMVemJ

render() { const history = this.state.history; const current = history[this.state.stepNumber]; const winner = calculateWinner(current.squares); const moves = history.map((step, move) => { let rowCol = this.setRowCol(); // returns row, col string for step const desc = move ? 'Go to move #' + move + rowCol: 'Go to game start'; return ( <li key={move + rowCol}> <button onClick={() => this.jumpTo(move)}>{desc} </button> </li> ); }); // [...omitted code that sets the status variable...] 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> <ol>{moves}</ol> </div> </div> ); 
1
  • Can you put up a code sandbox of your code please? Commented Sep 8, 2018 at 13:36

1 Answer 1

1

A simple solution is to remember which square was clicked in the history, alongside the squares key. And then use this index to retrieve which row and col was clicked.

Here is a working example: https://codepen.io/anon/pen/LJOodG?editors=0010

setRowCol only evaluates the last 2 steps of the history where are rendering the button list and should evaluate what was played at the time of the step. setRowCol should take the current evaluated button into account. I updated your code to match this behavior: codepen.io/anon/pen/RYjXMb?editors=0010#0

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

3 Comments

Ok I get it, setRowCol only evaluates the last 2 steps of the history where are rendering the button list and should evaluate what was played at the time of the step. setRowCol should take the current evaluated button into account. I updated your code to match this behavior: codepen.io/anon/pen/RYjXMb?editors=0010#0
Also note the difference in complexity between my first and second codepens
Thanks, this helped me understand how React updates the UI.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.