How to call a React Child Function (2024)

If you want to call a function of a child component from a parent component in React, you can use the useImperativeHandle hook.

Let’s say we have a simple Listing component that renders a random todo item from the JSONPlaceholder API.

import { View, Text, StyleSheet } from 'react-native';import React, { useEffect, useState } from 'react';type Listing = {userId: number;id: number;title: string;completed: boolean;};const Listing = () => {const [data, setData] = useState<Listing>();const loadData = async () => {const id = Math.floor(Math.random() * 200) + 1;const data = await fetch(`https://jsonplaceholder.typicode.com/todos/${id}`);const json = await data.json();setData(json);};useEffect(() => {loadData();}, []);return (<View style={styles.container}>{data ? (<Text style={{ fontSize: 20, color: '#fff' }}>{data.title}</Text>) : (<Text style={{ fontSize: 20, color: '#fff' }}>Loading...</Text>)}</View>);};const styles = StyleSheet.create({container: {backgroundColor: '#101353',alignItems: 'center',padding: 20,margin: 20}});export default Listing;

Now we want to call the loadData function from the parent component - but how?

The easiest way is to use the useImperativeHandle hook. It allows you to expose certain functions to the parent component.

To use it, we need to wrap our component in a forwardRef call and pass the ref to the useImperativeHandle hook.

import { View, Text, StyleSheet } from 'react-native';import React, { useEffect, useState } from 'react';import { forwardRef, useImperativeHandle } from 'react';type Listing = {userId: number;id: number;title: string;completed: boolean;};interface Props {}// Define the ref typeexport type ListingRef = {refresh: () => void;};// Wrap the component in a forwardRef callconst ListingGood = forwardRef<ListingRef, Props>((props, ref) => {const [data, setData] = useState<Listing>();const fetchData = async () => {...};// Pass the ref to the useImperativeHandle hookuseImperativeHandle(ref, () => ({refresh: () => {fetchData();}}));return (...);});const styles = StyleSheet.create({container: {backgroundColor: '#ff00ff',alignItems: 'center',padding: 20}});export default ListingGood;

Within the useImperativeHandle hook we can then define the functions that we want to expose to the parent component.

Now our parent component only needs to create a ref and pass it to the child component:

import { View, Button } from 'react-native';import React, { useRef, useState } from 'react';import ListingGood, { ListingRef } from '../components/ListingGood';const Page = () => {// Create the refconst ref = useRef<ListingRef>(null);// Use the refconst updateMyChild = () => {ref.current?.refresh();};return (<View><Button onPress={updateMyChild} title="Update child component" />{/* Add the ref */}<ListingGood ref={ref} /></View>);};export default Page;

Check out the useImperativeHandle docs for more information as well!

How to call a React Child Function (2024)
Top Articles
Here's Why a $20,000 Emergency Fund Might Fail You
Controller: Job Description and Average Salary
Fighter Torso Ornament Kit
Food King El Paso Ads
Robot or human?
Senior Tax Analyst Vs Master Tax Advisor
Jesus Calling December 1 2022
Richard Sambade Obituary
Red Wing Care Guide | Fat Buddha Store
Soap2Day Autoplay
Devourer Of Gods Resprite
Craigslist Estate Sales Tucson
Blog:Vyond-styled rants -- List of nicknames (blog edition) (TouhouWonder version)
Lenscrafters Huebner Oaks
2021 Lexus IS for sale - Richardson, TX - craigslist
Used Sawmill For Sale - Craigslist Near Tennessee
Video shows two planes collide while taxiing at airport | CNN
Yakimacraigslist
Trivago Sf
Traveling Merchants Tack Diablo 4
Accident On 215
The Ultimate Guide to Extras Casting: Everything You Need to Know - MyCastingFile
Putin advierte que si se permite a Ucrania usar misiles de largo alcance, los países de la OTAN estarán en guerra con Rusia - BBC News Mundo
Craigslist Org Appleton Wi
Seeking Arrangements Boston
Greyson Alexander Thorn
Caring Hearts For Canines Aberdeen Nc
Everything To Know About N Scale Model Trains - My Hobby Models
From This Corner - Chief Glen Brock: A Shawnee Thinker
Churchill Downs Racing Entries
Craigslist Boerne Tx
Omnistorm Necro Diablo 4
Craigs List Stockton
The Syracuse Journal-Democrat from Syracuse, Nebraska
Scottsboro Daily Sentinel Obituaries
Skill Boss Guru
Pepsi Collaboration
Td Ameritrade Learning Center
The Largest Banks - ​​How to Transfer Money With Only Card Number and CVV (2024)
Bob And Jeff's Monticello Fl
Directions To Cvs Pharmacy
Deepwoken: How To Unlock All Fighting Styles Guide - Item Level Gaming
Uc Davis Tech Management Minor
Sound Of Freedom Showtimes Near Amc Mountainside 10
Ts In Baton Rouge
Backpage New York | massage in New York, New York
Hdmovie2 Sbs
Diario Las Americas Rentas Hialeah
Festival Gas Rewards Log In
Marion City Wide Garage Sale 2023
7 National Titles Forum
Latest Posts
Article information

Author: Moshe Kshlerin

Last Updated:

Views: 5549

Rating: 4.7 / 5 (57 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Moshe Kshlerin

Birthday: 1994-01-25

Address: Suite 609 315 Lupita Unions, Ronnieburgh, MI 62697

Phone: +2424755286529

Job: District Education Designer

Hobby: Yoga, Gunsmithing, Singing, 3D printing, Nordic skating, Soapmaking, Juggling

Introduction: My name is Moshe Kshlerin, I am a gleaming, attractive, outstanding, pleasant, delightful, outstanding, famous person who loves writing and wants to share my knowledge and understanding with you.