MrRobot9
MrRobot9

Reputation: 2684

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?

Upvotes: 2

Views: 10661

Answers (2)

Jayavel
Jayavel

Reputation: 3407

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.

Upvotes: 5

Harish Soni
Harish Soni

Reputation: 1896

You need to assign the value to the ref. You are passing ref as a function.

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

  state = {
    dom: null
  };

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

  componentDidMount() {
    this.check();
  }

  check() {
    const innerHTML = ReactDOM.findDOMNode(this.myRef).innerHTML;
    setTimeout(
      () => (ReactDOM.findDOMNode(this.myRef).innerHTML = "TEST"),
      1000
    );
    console.log(innerHTML);
    this.setState({
      dom: innerHTML
    });
    {
      this.drawBackground();
    }
  }

  render() {
    return (
      <div>
        <h1 ref={ref => (this.myRef = ref)} id="foo">
          bar
        </h1>{" "}
        //You need to assign the value of the ref to the instance variable
      </div>
    );
  }
}

Upvotes: 4

Related Questions