Friday, November 29, 2024
Google search engine
HomeLanguagesHow to Call Function Inside Child Component from Parent Component using useRef...

How to Call Function Inside Child Component from Parent Component using useRef hook ?

In ReactJS, we can pass the function reference from parent components to child components. However, there are scenarios where you may need to call the function inside the child component from the parent component. In this article, we will explore how to achieve this in ReactJS.

Approach to Call Function Inside Child Component from Parent Component

Following are the steps to call the function inside the child component from the parent component.

  • In the parent component, create a useRef hook.
  • Pass this reference to the child component as props.
  • Use that reference in the child component wherever required.

Example

  • In this example, Parent component is passing reference using useRef hook and useState function as props to the child component. This reference is assigned to the button in the child component which will be hidden by CSS property display-none.
  • In the child component, there is an input field and one state variable. The input on the change function will set the state variable with that input value.
  • By clicking on the button in the child component, it will set the state variable which is in the parent component.
  • There is a button in the parent component. Here, we are trying to click the button in the child component programmatically from the parent component using the ref.
  • When we click on the button in the parent component it will call the child component onclick function and sets the parent component state variable.

Creating React Application

Step 1: Create a React application using the following command.

npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command:

cd foldername

Project Structure: It will look like the following.

MicrosoftTeams-image-(14).png

Filepath – src/App.js:

Javascript




import './App.css';
import Parent from './Parent';
  
function App() {
    return (
        <div>
        {/*Rendering the Parent component  */}
            <Parent />
        </div>
    );
}
  
export default App;


Filepath – src/Parent.js:

Javascript




import { useRef, useState } from 'react';
import Child from './Child';
function Parent() {
    const [name, setname] = useState("");
    const childref = useRef();
  
    return (
        <div style={{margin:"20px"}}>
          
            <div>Parent Component</div>
              
            {/* Displayed name which was written in 
            child component input field*/}
            {name !== '' && <div>{name}</div>}
              
            {/* By clicking on this button, the onclick 
            method will click the button in the child 
            component using useRef hook*/}
            <button onClick={() => { childref.current.click() }}
             style={{ margin: "2px" }}>
             Display name
            </button>
              
            {/* Rendering the child component */}
            <Child reference={childref} setname={setname} />
        </div>
    )
}
export default Parent;


Filepath – src/Child.js:

Javascript




import { useState } from 'react';
function Child(props) {
    const [input, setinput] = useState("");
  
    return (
        <div style={{ marginTop: "30px" }}>
  
            <div>Child Component</div>
            {/*The input onchange function will set 
            the input state variable*/}
            <input type="text" onChange=
                {(e) => { setinput(e.target.value) }}>
            </input>
  
            {/* This has reference which is 
            sent by Parent as props*/}
            <button ref={props.reference} 
                style={{ display: "none" }}
                onClick={() => { props.setname(input) }} >
            </button>
        </div>
    )
}
export default Child;


Output:

React-App---Google-Chrome-2023-06-25-09-55-04.gif

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments