Peter Wu
Peter Wu

Reputation: 49

Save each index into each button

I'm currently working on a Tic Tac Toe game and want to display index in each of the button, like below. I'm using React right now.

<button id="button" index="0" nav-selectable="true" class="Square_Square__1MfjH"></button>
<button id="button" index="1" nav-selectable="true" class="Square_Square__1MfjH"></button>
...
<button id="button" index="8" nav-selectable="true" class="Square_Square__1MfjH"></button>

Here is my code:

const Square = (props) => {
    return (
        <div>
            <button 
                id="button"
                nav-selectable="true"
                key={props.index} // Display this in the button
                className={classes.Square} 
                onClick={() => { props.onClick(); }}
                >
                {props.value}
            </button>
        </div>
    )
}
class Board extends Component {
    renderSquare(i) {
        return <Square 
            index={i} // Take the i from below (0,1,2,3,4,5,6,7,8)
            value={this.props.squares[i]}        
            onClick={() => { this.props.onClick(i); }}
            />;
    }

    render() {
        return (
            <div>
                <div className={classes.Board}>
                    {this.renderSquare(0)}
                    {this.renderSquare(1)}
                    {this.renderSquare(2)}
                </div>
                <div className={classes.Board}>
                    {this.renderSquare(3)}
                    {this.renderSquare(4)}
                    {this.renderSquare(5)}
                </div>
                <div className={classes.Board}>
                    {this.renderSquare(6)}
                    {this.renderSquare(7)}
                    {this.renderSquare(8)}
                </div>
            </div>
        )
    }
}

However, this method seems not working. Can anyone help me out? Thanks!

Upvotes: 0

Views: 47

Answers (1)

Tamas Szoke
Tamas Szoke

Reputation: 5542

If you want it as an attribute, you can use index or data-index.

Change your square example to:

<button 
  id="button"
  nav-selectable="true"
  key={props.index} // Display this in the button
  index={props.index}
  className={classes.Square} 
  onClick={() => { props.onClick(); }}
>
  {props.value}
</button>

Upvotes: 2

Related Questions