The Wayback Machine - https://web.archive.org/web/20240711181539/https://www.geeksforgeeks.org/how-to-pass-data-from-one-component-to-other-component-in-reactjs/
Open In App

How to pass data from one component to other component in ReactJS ?

Last Updated : 06 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In React, passing data from one component to another component is a common task. It helps build a dynamic and interactive web application. We can pass data in components from parent to child, child to parent, and between siblings as shown below.

Project Structure

It will look like the following. We have created two Components named Child.js and Parent.js as shown below.

We have created two Components named Child.js and Parent.js as shown in the above structure.

Approachs to pass data between components in react

1. Passing data from Parent to Child in React

For passing data from parent to child component, we use props. Props data is sent by the parent component and cannot be changed by the child component as they are read-only.

Example: The following example covers how to pass data from Parent to Child Component in ReactJS.

CSS




/* App.css*/
.App {
    text-align: center;
}
 
.geeks {
    color: green;
}


Javascript




// App.js
import React from "react";
import "./index.css";
import Parent from "./Parent";
import "./App.css";
 
const App = () => {
    return (
        <div className="App">
            <h1 className="geeks">Geeksforgeeks</h1>
            <h3>This is App.js Component</h3>
            <Parent />
        </div>
    );
};
 
export default App;


Javascript




// Parent.js
import React from "react";
import Child from "./Child";
 
const Parent = () => {
    const data = "Data from Parent to Child";
    return (
        <div>
            <h4>This is Parent component</h4>
            <Child data={data} />
        </div>
    );
};
 
export default Parent;


Javascript




// Child.js
import React from "react";
 
const Child = (props) => {
    return <h3> {props.data} </h3>;
};
 
export default Child;


Step to Run Application: Run the application using the following command from the root directory of the project

npm start

Output: This output will be visible on http://localhost:3000/

Screenshot-from-2023-10-06-10-46-32

2. Passing data from Child to Parent Component

For passing the data from the child component to the parent component, we have to create a callback function in the parent component and then pass the callback function to the child component as a prop. This callback function will retrieve the data from the child component. The child component calls the parent callback function using props and passes the data to the parent component.

Example: The following example covers how to pass data from Child to Parent Component in ReactJS.

CSS




/* App.css */
.App {
    text-align: center;
}
.container {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: center;
}
 
.item {
    min-width: 33rem;
    text-align: left;
}
 
.geeks {
    color: green;
}


Javascript




// App.js
import React from "react";
import "./index.css";
import Parent from "./Parent";
import "./App.css";
 
const App = () => {
    return (
        <div className="App">
            <h1 className="geeks">GeeksforGeeks</h1>
            <Parent />
        </div>
    );
};
 
export default App;


Javascript




// Parent.js
 
import React from "react";
import Child from "./Child";
 
class Parent extends React.Component {
    state = {
        msg: "",
    };
    handleCallback = (childData) => {
        this.setState({ msg: childData });
    };
    render() {
        const { msg } = this.state;
        return (
            <div>
                <Child
                    parentCallback={this.handleCallback}
                />
                <h1> {msg}</h1>
            </div>
        );
    }
}
 
export default Parent;


Javascript




// Child.js
 
import React from "react";
 
class Child extends React.Component {
    onTrigger = () => {
        this.props.parentCallback("Welcome to GFG");
    };
    render() {
        return (
            <div>
                <br></br> <br></br>
                <button onClick={this.onTrigger}>
                    Click me
                </button>
            </div>
        );
    }
}
 
export default Child;


Step to Run Application: Run the application using the following command from the root directory of the project

npm start

Output: This output will be visible on http://localhost:3000/

Peek-2023-10-06-11-11

3. Passing data between Siblings

For passing data among siblings, there are multiple methods we can choose from as shown below:

  • Combination of the above two methods (callback and use of props).
  • Using Redux.
  • ContextAPI

Here we will use context API to pass the data. When the button in child1 is clicked it will update the data in the Child2 component.

Folder Structure

It will look like the following. We have created two Components named Child1.js and Child2.js as shown below.

ezgifcomgifmaker

Example: In this example we will use context API to pass the data from one sibling Child1 to other sibling Child2.

CSS




/* App.css */
.App {
    text-align: center;
}
 
.geeks {
    color: green;
}


Javascript




// App.js
 
import { React, useState, createContext } from "react";
import "./index.css";
import Child1 from "./Child1";
import "./App.css";
import Child2 from "./Child2";
 
// Create a new context and export
export const NameContext = createContext();
 
// Create a Context Provider
const NameContextProvider = ({ children }) => {
    const [name, setName] = useState(undefined);
 
    return (
        <NameContext.Provider value={{ name, setName }}>
            {children}
        </NameContext.Provider>
    );
};
 
const App = () => {
    return (
        <div className="App">
            <h1 className="geeks">GeeksforGeeks</h1>
            <NameContextProvider>
                <Child1 />
                <Child2 />
            </NameContextProvider>
        </div>
    );
};
 
export default App;


Javascript




// Child1.js
 
import React, { useContext } from "react";
import { NameContext } from "./App";
 
const Child1 = () => {
    const { setName } = useContext(NameContext);
    function handle() {
        setName("Geeks");
    }
    return (
        <div>
            <h3>This is Child1 Component</h3>
            <button onClick={() => handle()}>Click </button>
        </div>
    );
};
 
export default Child1;


Javascript




// Child2.js
 
import React, { useContext } from "react";
import { NameContext } from "./App";
 
const Child2 = () => {
    const { name } = useContext(NameContext);
 
    return (
        <div>
            <br />
            <h4>This is Child2 Component</h4>
            <h4>hello: {name}</h4>
        </div>
    );
};
 
export default Child2;


Step to Run Application: Run the application using the following command from the root directory of the project

npm start

Output: This output will be visible on http://localhost:3000/Peek-2023-10-06-12-07



Similar Reads

How to pass data from child component to its parent in ReactJS ?
In ReactJS, data flow between components is typically unidirectional, meaning data is passed from parent components to child components. However, there are scenarios where you may need to pass data from a child component back to its parent component. Approach:Following are the steps to pass data from the child component to the parent component: In
2 min read
Pass by Value and Pass by Reference in Javascript
JavaScript, being a versatile and dynamic programming language, employs different strategies for passing variables to functions. Two common approaches are "pass by value" and "pass by reference". Understanding these concepts is important for writing efficient and bug-free code. Pass By ValueWhen a function is called, the value of the variable is di
4 min read
How to pass props to ReactJS component that wrapped in variable ?
To pass props to a React JS component that is wrapped in a variable we have to create some copy of the component that can be modified. As we can't access the props of that component and pass a required argument we can clone it to make the required element and use it in our application. Props: Props means properties. Prop is an argument that we pass
2 min read
How to Pass Value from One Child Component to Another in VueJS ?
Vue.js is a JavaScript framework used in building powerful and beautiful user interfaces. The key feature of Vue.js is its component-based architecture that allows the developers to create reusable and modular components. In this article, we will learn how to pass value from one child component to another in VueJS. There are sometimes when we need
3 min read
How to pass a react component into another to transclude the first component's content?
There are two ways by which we can pass a react component into another component. Creating React Application: Before proceeding to the approach you have to create a React app. 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
2 min read
How to pass property from a parent component props to a child component ?
Passing props from parent to child in React JS is an important concept. Props are read-only properties that are sent from the parent components to the child components. We can pass props in from parent to child using React JS functional as well as class components Table of ContentPassing Property Using Class ComponentsPassing Property Using Functio
3 min read
How to pass data from Parent to Child component in Angular ?
We can use the @Input directive for passing the data from the Parent to Child component in Angular Using Input Binding: @Input - We can use this directive inside the child component to access the data sent by the parent component. Here app.component is the Parent component and cdetail.component is the child component. Parent Component app.component
3 min read
Write a program to pass values to child using context in ReactJS ?
Passing values to chile in react js is an important concept in react js. It simply can be achieved by using prop drilling but it is not the right way in case of big project. Hence we will pass the values to child using context in react js with the help of useContext Hook. PrerequisitesReact JSReact JS useContext HookApproachTo pass values to child
4 min read
How to pass multiple props in a single event handler in ReactJS?
To pass multiple props in a single event handler in ReactJS we can create a function to handle the event that accepts multiple props or calls multiple methods. It is a normal task while creating a react project to perform multiple operations for some events. PrerequisitesReact JSReact JS PropsTo pass/call the multiple props methods in a single even
2 min read
How to Reference a Specific Object to Pass Down as Properties in ReactJS ?
ReactJS, a widely used JavaScript library, employs Props, enabling the passing of data from parent to child components. Props are read-only, facilitating data access by child components via 'this.props.' The ReactJS library has two components: Functional ComponentClass ComponentSteps to Create the React Application:Step-1: Create a React Applicatio
3 min read
three90RightbarBannerImg