Jarmojo
Jarmojo

Reputation: 91

Call a parent component function from a child component

Fairly new to React. I have a lottery wheel as part of a hobby project website: The Wheel object was downloaded with npm:

npm install lottery-wheel
import Wheel from 'lotter-wheel'
class Lottery extends Component {
   constructor() {
     bla bla 
   }
  
  componentDidMount() {
     new Wheel( {
        el: document.querySelector("#wheel"),
            onSuccess(data) {
              alert(`Congratulations, you picked up ${data.text}`)
              /* I want to pass the data here to Parent */ 
            },
            onButtonHover(anime, button) {
                anime({
                  targets: button,
                  scale: 1.3,
                  perspective: 80,
                  duration: 400
                });
            },
     });
  }

  render() {
  
    return (
      <div id="wheel"></div>
    )
  }
}

SO, In the callback-function 'onSuccess' I want to pass the 'data' from the Wheel child component to the 'Lottery' parent component.

How can I do this? I know how props work but not in this case.. Can I use a hook, in that case, how? I want avoid downloading and going into 'Wheel' definition since it was not created by me.

Upvotes: 2

Views: 64

Answers (1)

Drew Reese
Drew Reese

Reputation: 203476

Define a function and set as the onSuccess callback in the Wheel.

class Lottery extends Component {
  successHandler = data => {
    alert(`Congratulations, you picked up ${data.text}`);
  };

  componentDidMount() {
    new Wheel({
      el: document.querySelector("#wheel"),
      data: [{
        text: 'apple',
        chance: 20
      }, {
        text: 'banana'
      }, {
        text: 'orange'
      }, {
        text: 'peach'
      }],
      onSuccess: this.successHandler,
      onButtonHover(anime, button) {
        anime({
          targets: button,
          scale: 1.3,
          perspective: 80,
          duration: 400
        });
      }
    });
  }

  render() {
    return <div id="wheel"></div>;
  }
}

Edit call-a-parent-component-function-from-a-child-component

Upvotes: 1

Related Questions