Search code examples
javascriptreactjsreact-nativemethodsref

How create ref to call a function of a functional composant?


After upgrading react native 0.60. I try to change all my class composent to a functional composant. For my animation I like to use methods of a composant (I know its not really recommended but I prefer that than create a state variable and pass it as a props...).

For exemple here is my class composant:

class Child extends PureComponent {
  animateOpen = () => {

  }
  render() {
    return (
      <View>
        {...}
      </View>
    );
  }
}

const PlayButton = ({ status, onPress }) => {
  const childRef = useRef(null);

  return (
    <View>
      <Button onPress={this.childRef.animateOpen} />
      <Child ref={childRef}/>
    </View >
  );
};

So in this exemple, How can I do to wrote Child composant as a functional composant ?


Solution

  • Child component as a functional component:

    const Child = () => {
      const animateOpen = () => {}
    
      return (
        <View>
          {...}
        </View>
      )
    }