Search code examples
javascriptreactjsdomreact-component

Reactjs: Uncaught TypeError: Cannot set property 'innerHTML' of null


import React, { Component } from 'react';
import ReactDOM from 'react-dom';

export default class Game extends Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
    this.check = this.check.bind(this);
  }


 drawBackground() {
    console.log("worked");
}

  check () {
    this.myRef.current.innerHTML  = "Testing";
    {this.drawBackground()}      
  }

  render() {
    return (
        <div>
          <h1 ref={this.myRef} id="foo">bar</h1>
          {this.check()}
</div>
    );
  }
}

I need to access the text inside h1 tag in the check function, but I get this error Reactjs: Uncaught TypeError: Cannot set property 'innerHTML' of null. I followed the documentation. Am I missing something?


Solution

  • The ref is first set after the first render()

    check the demo once demo

    You're referring the ref immediately after it is declared, Since the ref object receives the mounted instance of the component as its current.

    If you're trying to access the DOM at the same time it's trying to generate it. this.myRef will not return anything because the component has no real DOM representation in render.