user1524441
user1524441

Reputation: 25

Accessing child state using Refs - Cannot read property 'value' of undefined

Newbie to React:

Error Cannot read property 'value' of undefined

This occurs after I click on one of the Cell components. I'm wanting to print this.tl.state.value to the console.

Parent Component

class App extends Component {
  constructor(props) {
    super(props);
    this.tl = React.createRef();
  }

  checkForWinner = () => {
    console.log("Checking for winner..." + this.tl.state.value);
  }
  
  render() {
    return (
      <div className="App">
        <Cell ref={this.tl} winnercheck={this.checkForWinner} />
      </div>
    );
  }
}

Child Component

class Cell extends Component {
    constructor(props) {
        super(props);
        this.state = {
            value: "X"
        }
    }

    toggleVal = () => {

        this.props.winnercheck();
    }
    
    render() {
        return (
            <div onClick={() => this.toggleVal()}>
                {this.state.value}
            </div>
        );
    }
}

Upvotes: 0

Views: 622

Answers (1)

Robert May
Robert May

Reputation: 819

To access the value of a ref, you need to use ref.current. In your case, that would be this.tl.current. Read the documentation for more information.

Upvotes: 1

Related Questions