0

After a lot of googling, I can't find a solution. I need to call a child function from the parent component. Both are class components.

Some code

    constructor(props) {
      super(props)
      this.childRef = React.createRef();
      this.setAbilities();
    }

Rendering child component

{this.props.enemyChamp.abilities.map(ab => (
                            <AbilityButton
                            ref={this.childRef}
                            onCast={(caster, ability)=>this.castAbility(caster, ability)}                               
                            index={this.abilities[ab].id}
                            />
                        ))}

Function I want to call in AbilityButton.js

    castEnemyAbility = (ability, abIndex) => {
    var caster = "enemy";
    if(this.props.onCast(caster, ability)) {
        this.startCooldown(abIndex);
        this.cdTimer = setTimeout(() => {
            
        }, this.getAb().coolDown)
    }
}

exporting parent component

export default connect(mapStateToProps, {
setAbilities,
doDamage, heal,
regenMana, regenHealth

}, null, {forwardRef: true})(Fight);

I tried with and without {forwardRef: true}, Tried with an alternative method of rendering the Child component:

 <AbilityButton
                            wrappedComponentRef={ref => this.childRef = ref}
                            onCast={(caster, ability)=>this.castAbility(caster, ability)}                               
                            index={this.abilities[ab].id}
                            />

I tried so many combinations, and after lots of trial and error and a lot of googling, I decided to ask for help.

this.childRef.current always returns null. Any advice? I'm tired of trying

redmaster
  • 95
  • 1
  • 12

0 Answers0