React component not rerendering on click

Hello y’all, im tryin got build a tic tac toe game with react and can’t seem to get this.state to rerender within the component. any tips would be greatly appreciated!

import React, { Component } from "react";

class Box extends Component {
  constructor(props) {
    super(props);
    this.state = { currentLetter: "-" };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    console.log(this.state.currentLetter)
    this.setState(() => {
      if (this.state.currentLetter === "-") this.state.currentLetter = "X";
      else if (this.state.currentLetter === "X") this.state.currentLetter = "O";
      else this.state.currentLetter = "X"
    });
  }

  render() {
    return (
      <div>
        <h1>Tic Tac Toe</h1>
        <button style={{ height: "100px" }} onClick={this.handleClick}>
          {this.state.currentLetter}
        </button>
      </div>
    );
  }
}

export default Box;

You’re just mutating the state object (this.state.currentLetter = "X"). This is not what any React tutorials or docs tell you to do. The reason for that is, if you mutate, state is exactly the same object. The fact a property on the object has changed is neither here nor there. React has no idea it needs to update

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.