Search code examples
javascriptreactjstypeerrorgsap

Creating an on click event on ref


https://codesandbox.io/s/k0q179orqv

What I'm trying to do:
Create an onclick event and handler to just begin the gsap animation. In other words, all the handler will do is this:

beginAnimation (){
  this.tl.play()
}

What I've tried to do: I started by adding a ref in About.js, and it gets forwarded to Card.js and is on the arrow I want to be able to click to begin animation. The refs are passed down in an object, and accessed like this "ref.ref2"

I've attempted to do something like this:

Create a method in About.js:

  beginAnimation() {
    this.tl.play();
  }

and pass it to the Cards being rendered:

 createCards(card, i) {
    return (
      <Card
        id={i}
        key={i}
        card={card}
        info={this.state.aboutCards}
        ref={{ ref1: this["card" + i], ref2: this.button }}
        beginAnimation={this.beginAnimation}
      />
    );
  }
}

Then in Card.js:

      <div className="prevnext">
        <button
          className="pn-btn"
          id="prev"
          ref={ref.ref2}
          onClick={props.beginAnimation}
        />

but i receive an error: TypeError: Cannot read property 'tl' of undefined

I'm very new to react, and refs confuse the life out of me for some reason


Solution

  • When you pass down a function to another component, this refers to the component that invoked it (the child), not the component that "owns" that function.

    You can fix this 2 ways, either wrap your prop around an arrow function to encapsulate the this value of the parent component:

    onClick={() => props.beginAnimation()}
    

    Or bind the this value to the function in the constructor:

    this.beginAnimation = this.beginAnimation.bind(this)