0
votes

Having a little problem with my Tic Tac Toe game using React. So every time I click on the board I have X render which I want it to do. but I only want it to. render in one square not all of them. Should I use setState for this particular situation or is their another way to call in x

Here is my code:

class App extends Component {
    render() {
        return (<div>
            <h1>TIC TAC TOE</h1>
            <ApplicationComponent/>
            <GridComponent/>
        </div>)
    }
}
class ApplicationComponent extends React.Component {

    render() {
        return (<div>Application Component</div>);
    }
    resetBoard() {
        console.log("resetBoard");
    }
    checkingWon() {
        console.log("checkingWon")
    }
}
class GridComponent extends React.Component {

    constructor() {
        super();
        this.state = {
            turn: '',
        };
    }
    setMark(i) {
        this.setState({turn: "X"
        })
    }

    render() {

        // empty object
        let grid = [];
        // set length for loop
        let length = 9;
        // loop through array and push in objects


        for(let i = 0; i < length; i++) {
            grid.push(<BoxComponent onUpdateNeeded={this.setMark.bind(this, i)} name={this.state.turn}/>);

        }

        // render
        return (

            <div className="grid">


                {grid.map(function(component, index){
                    return <div key={index}> {component} </div>;
                })}
            </div>
        );
    }
}

class BoxComponent extends React.Component {


    Clicked(event) {
        this.props.onUpdateNeeded();
        console.log(this);

    }

    render() {
        return (

            <div className="box" onClick={this.Clicked.bind(this)}>
                {this.props.name}

            </div>
        );
    }
}

export default App;
1
You'll want to keep track of each location, probably in an object since they are easier to manipulate, and then update the state accordinglyfungusanthrax

1 Answers

1
votes

As @fungusanthrax said in the comments, you'd have to save the grid in state. Basically have a list with the boxes (an array for example) that would get populated with the current player/turn (X/O in this case) at the index when clicked.

You can take a look at this example.