Categories
JavaScript Answers React Native Answers

How to call child component function from parent component in React Native?

Spread the love

Sometimes, we want to call child component function from parent component in React Native.

In this article, we’ll look at how to call child component function from parent component in React Native.

How to call child component function from parent component in React Native?

To call child component function from parent component in React Native, we can use the useImperativeHandle hook.

For instance, we write:

import * as React from 'react';
import { View, Button } from 'react-native';
import Constants from 'expo-constants';
import { Card } from 'react-native-paper';

const Child = React.forwardRef((props, ref) => {
  const { foo } = props;
  React.useImperativeHandle(ref, () => ({
    method: () => {
      console.log(foo);
    },
  }));

  return <View></View>;
});

export default function App() {
  const ref = React.useRef();
  const onPress = () => {
    ref.current.method();
  };

  return (
    <View style={{ flex: 1 }}>
      <Button onPress={onPress} title="Hello" />
      <Child foo="bar" ref={ref} />
    </View>
  );
}

to create the Child component with forWardRef with a function that takes the props and ref.

In it, we call useImperativeHandle with ref and a function that returns the methods we can call from the ref assigned to the Child component.

Next, we create a ref with useRef in App.

And then we call ref.current.method in onPress which is run when we press the button.

We add Child beneath Button and assign a ref to it to let us call ref.current.method.

Conclusion

To call child component function from parent component in React Native, we can use the useImperativeHandle hook.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *