Pass Data From Child to Parent Component in React

React is a powerful JavaScript library for making user interfaces, and it’s great at keeping track of component structures. It’s common to pass data from child to parent component. This article will talk about three popular ways to do this:

1. Using Callback Functions: In this way, a callback function is sent as a prop from the parent component to the child component. After that, the child component can call the callback method and send information back to the parent component.

2. Using the Context API: React comes with the Context API built-in feature, which lets components share data without having to pass props through each level of the component tree. It allows the creation of a global state accessible to all components within a particular context.

3. Adding a State Management Library like Redux: Redux is a well-known tool for managing states in React apps. It provides a centralized store to manage the application state, which makes it easier for components to share data and pass data from child components to parent components.

In React, these methods offer different ways to pass data from child components to parent components. You should pick the way that fits your needs the best because each one has its own benefits and situations where it works best.

1. Using Callback Functions

The first and most straightforward method involves using callback functions.

In the parent component, create a function that will receive the data from the child component. This function will be passed down to the child component as a prop. here we enter the input value from the child and on click event we send the value to the parent component

import React, { useState } from 'react'
import ChildComponent from './ChildComponent'
const ParentComponent = () => {
    const [dataFromChild,setDataFromChild] = useState('');
    const handleDataFromChild = (data)=>{
        setDataFromChild(data);
    }
  return (
    <div>
        <h3>ParentComponent</h3>
        <ChildComponent onDataFromChild={handleDataFromChild}/>
        <p>Data From Child: {dataFromChild}</p>
    </div>
  )
}

export default ParentComponent

In ParentComponent, we initialize a state variable dataFromChild using useState. This state will hold the data received from the child component. handleDataFromChild is a function that takes data as an argument and updates the dataFromChild state when called. handleDataFromChild function will be passed to the child component.

When the child component sends data using onDataFromChild(inputValue), it triggers the handleDataFromChild function in the parent component. This function updates the dataFromChild state.

Now In the child component, use the prop received from the parent to call the function and pass the data as an argument.

pass data from child to parent react
import React, { useState } from 'react'

const ChildComponent = ({onDataFromChild}) => {
    const [inputValue,setInputValue] = useState('');
    const sendDataToParent=()=>{
        onDataFromChild(inputValue)
    }
  return (
    <div>
        <h2>ChildComponent</h2>
        <input type="text" onChange={(e)=>setInputValue(e.target.value)}/>
        <button onClick={sendDataToParent}>Send Data to Parent</button>
    </div>
  )
}

export default ChildComponent

In ChildComponent, we initialize a state variable inputValue using useState. This state will hold the value of the input field.  When sendDataToParent is called, it triggers the onDataFromChild function received from the parent (via props) and passes inputValue as an argument.  When the button is clicked, sendDataToParent is called, initiating the data transfer to the parent component.

2. Using the Context API

import { createContext, useState } from 'react';
import './App.css';

import ParentComponent from './ParentComponent';
const appContext = createContext();
function App() {
  const [value,setValue] = useState('');
  const updateValue = (data) =>{
    setValue(data)
  }
  return (
    <appContext.Provider value={{value,updateValue}}>
      <ParentComponent/>
    </appContext.Provider>
  );
}

export default App;
export {appContext}

Here in the app.js file, we create a context using createContext(). appContext context will allow components to share data without explicitly passing props through each level of the tree.

import React, { useContext } from 'react'
import ChildComponent from './ChildComponent'
import {appContext} from './App'
const ParentComponent = () => {
    const context = useContext(appContext)
  return (
    
    <div>
        <h3>ParentComponent</h3>
        <ChildComponent/>
        <p>Data From Child: {context.value}</p>
    </div>
  )
}

export default ParentComponent

const context = useContext(appContext); This line uses the useContext hook to access the current context value (which includes value and updateValue) for the appContext.

import React, { useContext, useState } from 'react'
import {appContext} from './App'

const ChildComponent = () => {
    const context = useContext(appContext);
    const [inputValue,setInputValue] = useState('');
    
  return (
    <div>
        <h2>ChildComponent</h2>
        <input type="text" onChange={(e)=>setInputValue(e.target.value)}/>
        <button onClick={()=>context.updateValue(inputValue)}>Send Data to Parent</button>
    </div>
  )
}

export default ChildComponent

3. Adding a State Management Library like Redux

First, we need to install the Redux package in our project. we can do this by running the following command in our project directory:

npm install redux react-redux

Create a new directory called store in our project’s source folder (src). Inside the store directory, create a file named index.js. This file will contain the Redux store configuration.

import { createStore } from "redux";

const initialState = {
    data: '',
};

const reducer = (state = initialState, action) =>{
    switch(action.type){
        case'UPDATE_DATA':
        return{
            ...state,
            data:action.payload
        }
        default:
            return state;
    }
}

const store = createStore(reducer);
export default store;

In the ParentComponent.js file, import the necessary functions from the react-redux package and the Redux store from the store directory. Use the useSelector hooks to access the Redux store.

import React from 'react'
import ChildComponent from './ChildComponent'
import { useSelector } from 'react-redux'
const ParentComponent = () => {
    const data = useSelector((state)=>state.data);
  return (
    
    <div>
        <h3>ParentComponent</h3>
        <ChildComponent/>
        <p>Data From Child: {data}</p>
    </div>
  )
}

export default ParentComponent

In the ChildComponent.js file, import the necessary functions from the react-redux package. Use the useDispatch hook to update the input value using dispatch.

import React, {useState } from 'react'
import { useDispatch } from 'react-redux';

const ChildComponent = () => {
    const [inputValue,setInputValue] = useState('');
    const dispatch = useDispatch();
    const SendToParent = () => {
      dispatch({
        type:"UPDATE_DATA",
        payload:inputValue
      })
    }
  return (
    <div>
        <h2>ChildComponent</h2>
        <input type="text" onChange={(e)=>setInputValue(e.target.value)}/>
        <button onClick={SendToParent}>Send Data to Parent</button>
    </div>
  )
}

export default ChildComponent

Conclusion

passing data from child to parent components is a common requirement in React development. In this article, we explored three common methods to achieve this: using Callback Functions, the Context API, and integrating a State Management Library like Redux. Each method has its own advantages and use cases, so it’s important to choose the one that best fits your specific requirements.

You may also like:

Reactjs Guru
Reactjs Guru

Welcome to React Guru, your ultimate destination for all things React.js! Whether you're a beginner taking your first steps or an experienced developer seeking advanced insights.

React tips & tutorials delivered to your inbox

Don't miss out on the latest insights, tutorials, and updates from the world of ReactJs! Our newsletter delivers valuable content directly to your inbox, keeping you informed and inspired.

Leave a Reply

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

Table of Contents