The First Step is to Create a Parent Component
import React from 'react' const ParentComponent = () => { return ( <div> Hello Parent Component </div> ) } export default ParentComponent
The Second Step is to Use a Parent Component in Main App Component
import react from "react"; import ParentComponent from "./ParentComponent"; function App() { return <div><ParentComponent/></div>; } export default App;
Third Step Create Child Component
import React from 'react' const ChildComponent = () => { return ( <div> Hello Child Component </div> ) } export default ChildComponent
After Create All Components We Have to Create a Parent Component State
import React,{useState} from 'react' const ParentComponent = () => { const [stateName,setStateName]=useState("Hello World"); return ( <div> {stateName} </div> ) } export default ParentComponent
After creating State We Have To Add the Child Component Into the Parent Component and Pass State Data In to Child Component
import React,{useState} from 'react' import ChildComponent from './ChildComponent'; const ParentComponent = () => { const [stateName,setStateName]=useState("Hello World"); return ( <div> <ChildComponent stateName={stateName}/> </div> ) } export default ParentComponent
After creating State and Pass Data into Child Component, We Have to Get Data using Props
import React from 'react' const ChildComponent = (props) => { return ( <div> {props.stateName} </div> ) } export default ChildComponent
After Get Data from Parent to Child Using Props, If We Want to Share Data From Child To Parents We Have To Create One Handle That Change Parent State Data, So Create One Handle In Parent Component, and Pass Handle Into Child Component.
import React,{useState} from 'react' import ChildComponent from './ChildComponent'; const ParentComponent = () => { const [stateName,setStateName]=useState("Hello World"); const handleChangeData=(stateName)=>{ setStateName(stateName); } return ( <div> <ChildComponent stateName={stateName} handleChangeData={handleChangeData}/> </div> ) } export default ParentComponent
After Pass Handle into Child Component, We Have to Create One Button in Child Component, in This Button We Have to Create an onClick Event That Event Pass Handle That sends Data into Parent Component.
import React from 'react' const ChildComponent = (props) => { return ( <div> Parent Data in Child Component : {props.stateName}<br/> <button onClick={()=>props.handleChangeData("Hello World From Child Component")}>Data Send From Child</button> </div> ) } export default ChildComponent