1

I want to reuse some code in a react component via a custom function. However, when I run the following code, I get an error: this.runBubbles() is undefined.

class HomePage extends React.Component {

  runBubbles(){
    // instantiate some css bubbles on screen
  }

  clearAndRunBubbles(){
    // clear bubbles from DOM
    this.runBubbles()
  }

  componentDidMount(){
    this.runBubbles()
    // on resize, re-run bubbles code with new screen dimensions:
    window.addEventListener("resize",this.clearAndRunBubbles);
  }
}
5
  • 3
    Use this.runBubbles() Commented Aug 3, 2019 at 19:02
  • meant to put that in the first place, still throws an error. Which makes no sense since it's already been called in componentDidMount{} Commented Aug 3, 2019 at 19:04
  • 2
    Make sure you bind the functions with this keyword or else use arrow functions to avoid this binding. Commented Aug 3, 2019 at 19:05
  • Check componentDidMount, change runBubbles() to this.runBubbles() Commented Aug 3, 2019 at 19:06
  • making both runBubbles and clearAndRunBubbles arrow functions got it to work. Commented Aug 3, 2019 at 19:07

2 Answers 2

1

Try like this

class HomePage extends React.Component {

  runBubbles = () => {
    // instantiate some css bubbles on screen
  }

  clearAndRunBubbles = () =>  {
    // clear bubbles from DOM
    this.runBubbles()
  }

  componentDidMount(){
    this.runBubbles()
    // on resize, re-run bubbles code with new screen dimensions:
    window.addEventListener("resize", this.clearAndRunBubbles);
  }
}

For arrow function you don't need to have the this binding because by default it takes outer lexical scope.

or

class HomePage extends React.Component {

 constructor() {
   this.runBubbles = this.runBubbles.bind(this);
   this.clearAndRunBubbles = this. clearAndRunBubbles.bind(this);
 }

runBubbles(){
    // instantiate some css bubbles on screen
  }

  clearAndRunBubbles(){
    // clear bubbles from DOM
    this.runBubbles()
  }

  componentDidMount(){
    this.runBubbles()
    // on resize, re-run bubbles code with new screen dimensions:
    window.addEventListener("resize",this.clearAndRunBubbles);
  }
}

Whenever calling a standard function inside a class component in react you have to add this binding to make sure the function is binds to current class component.

Sign up to request clarification or add additional context in comments.

1 Comment

runBubbles = () => {} and clearAndRunBubbles = () => {} worked
0

On componentDidMount method, change runBubbles() to this.runBubbles()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.