Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 383
MrRobot9 Avatar asked Jan 20 '26 10:01

MrRobot9


2 Answers

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.

like image 133
Jayavel Avatar answered Jan 23 '26 00:01

Jayavel


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>
    );
  }
}
like image 35
Harish Soni Avatar answered Jan 23 '26 01:01

Harish Soni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!