Home » Javascript » javascript – ref undefined React

javascript – ref undefined React

Posted by: admin February 23, 2020 Leave a comment

Questions:

So the problem I am having is that I am trying to print the textContent of my ref every 5 seconds, and this works the very first time typeWrite() is called from componentDidMount(), but when it is called recursively (using setTimeout()), I get an error saying this.intro.current is undefined, even though it was defined the first time the function ran.

I want to keep the structure relatively similar (I don’t want to change it too much) because there are other things I have left out that rely on this structure.

export default class Home extends Component {
  constructor(props) {
    super(props);
    this.intro = React.createRef();
  }

  componentDidMount() {
    this.typeWrite();
  }

  typeWrite() {
    console.log(this.intro.current.textContent);
    setTimeout(this.typeWrite, 5000);
  }
  render() {
    return (
      <div className="intro" ref={this.intro}>Text</div>
    )
  }
}
How to&Answers:

You need to bind your function to your component.

  constructor(props) {
    super(props);
    this.intro = React.createRef();
    this.typeWrite = this.typeWrite.bind(this);
  }

or you need to call your function with arrow function.

  typeWrite() {
    console.log(this.intro.current.textContent);
    setTimeout(() => this.typeWrite(), 5000);
  }