React Native — Calling Child Function from Parent Component

 Introduction: In React Native, sometimes you need to call a child component’s function from the parent component. This can be achieved using React’s useImperativeHandle and forwardRef hooks. In this blog, we will learn how to do this by implementing a multi-select checkbox component.

Step 1: Creating the Child Component First, create a child component called Checkbox and define its initial state and functions:

import React, { useState, forwardRef } from 'react';
import { View, Text, TouchableOpacity } from 'react-native';

const Checkbox = forwardRef((props, ref) => {
const [isChecked, setIsChecked] = useState(false);

const toggleCheckbox = () => {
setIsChecked(!isChecked);
};

return (
<TouchableOpacity activeOpacity={0.5} onPress={toggleCheckbox}>
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
<View style={{ width: 24, height: 24, borderRadius: 5, borderWidth: 2, borderColor: '#000', alignItems: 'center', justifyContent: 'center' }}>
{isChecked && <View style={{ width: 18, height: 18, borderRadius: 5, backgroundColor: '#000' }} />}
</View>
<Text style={{ marginLeft: 8 }}>{props.label}</Text>
</View>
</TouchableOpacity>
);
});

Step 2: Modifying the Parent Component Next, modify the parent component (in this case, the App component) to include a reference to the child component using the useRef hook:

import React, { useRef } from 'react';
import { SafeAreaView, StyleSheet } from 'react-native';
import { Checkbox } from './Checkbox';

const App = () => {
const checkboxRef = useRef();

const getCheckboxValue = () => {
checkboxRef.current.parentChildFunction();
};

return (
<SafeAreaView style={styles.container}>
<Checkbox label="Check me" ref={checkboxRef} />
<TouchableOpacity style={styles.button} onPress={getCheckboxValue}>
<Text style={styles.buttonText}>Get Checkbox Value</Text>
</TouchableOpacity>
</SafeAreaView>
);
};

Step 3: Using the useImperativeHandle Hook Now, in the child component (Checkbox), use the useImperativeHandle hook to define the parentChildFunction:

import React, { useState, forwardRef, useImperativeHandle } from 'react';
import { View, Text, TouchableOpacity } from 'react-native';

const Checkbox = forwardRef((props, ref) => {
const [isChecked, setIsChecked] = useState(false);

const toggleCheckbox = () => {
setIsChecked(!isChecked);
};

useImperativeHandle(ref, () => ({
parentChildFunction: () => {
return isChecked;
},
}));

return (
// The same JSX code as before
);
});

By following these steps, you can effectively call a child component’s function from the parent component in React Native.

Happy coding!

To Know More, Check My YouTube Channel

Comments

Popular posts from this blog

Creating a Circular File Download Progress Bar using SVG in React Native

Best Practices for React Native Development Don’t and Do’s Prem Yathvik

Check the React native application is connected to the Internet.