1

I was working with the tic tac toe tutorial on the react web page of which the full code is here: https://codepen.io/gaearon/pen/VbbVLg?editors=0010

On line 9-13, this code appears that modifies the state of the class:

  render() {
    return (
      <button
        className="square"
        onClick={() => this.setState({value: 'X'})}
      >

I understand that on click, the method setState modifies the state. However, when I create a seperate method with the exact same code, it throws an error.

  test() {
    this.setState({value: 'X'})
  }

  render() {
    return (
      <button
        className="square"
        onClick={this.test}
      >
        {this.state.value}
      </button>

the code throws an error: TypeError: Cannot read property 'setState' of undefined

Why does the code throw this error?

Sarim Aleem
  • 158
  • 1
  • 5

0 Answers0