Folder Structure

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

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">w3wiki</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/



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

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.

Table of Content

  • Passing data from Parent to Child
  • Passing data from Child to Parent Component
  • Passing data between Siblings

Similar Reads

Project Structure

...

Approachs to pass data between components in react

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

Folder Structure

1. Passing data from Parent to Child in React...

Contact Us