0

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>
    )
  }
}
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Ken
  • 1,155
  • 2
  • 19
  • 36
  • 1
    Wrong duplicate, you want: [How to access the correct `this` inside a callback?](https://stackoverflow.com/q/20279484/1218980) – Emile Bergeron Feb 21 '20 at 20:26
  • 1
    So either define as an arrow function `typeWrite = () => { /* */ }` or define the callback as a new inline arrow function `setTimeout(() => this.typeWrite(), 5000)`. – Emile Bergeron Feb 21 '20 at 20:28

1 Answers1

1

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);
  }
hurricane
  • 6,521
  • 2
  • 34
  • 44