12 Parent Child - biswajitsundara/react GitHub Wiki

The react parent child communication is one of the most common use case.

  • The data can be passed from parent component to child component using props
  • Lets see below how it works from child component to parent component.

1. Simple UseCase

  • So we have two components - Manager Card (Parent) & Employee Card (Child)
  • The employee details renders on the screen and when we click on the button manager details
  • Then on the employee component it executes the parent function managerDetails
  • So we have passed the parent function as props to the child component
// ManagerCard.js
import { EmployeeCard } from "./EmployeeCard";

export const ManagerCard = () =>{
  const managerDetails = () =>{
      alert ('Manager Name is Elon Musk');
  }

  return <EmployeeCard managerHandler = {managerDetails}/>
}
// EmployeeCard.js
export const EmployeeCard = (props) => {
  return (
    <div>
      <h1>Employee Name: Biswajit Sundara</h1>
      <button onClick={props.managerHandler}>Manager Details</button>
    </div>
  );
};
//App.js
import { ManagerCard } from "./components/ManagerCard";

function App() {
  return <ManagerCard/>;
}

export default App;

2. Passing Parameters

If we want to pass parameter from child component to parent component then follow the below.

  • Here we will try to pass the employee name from the employee component to manager component
// Employee Card
export const EmployeeCard = (props) => {
  return (
    <div>
      <h1>Employee Name: Biswajit Sundara</h1>
      <button onClick={() => props.managerHandler('Biswajit')}>Manager Details</button>
    </div>
  );
};
// Manager Card
import { EmployeeCard } from "./EmployeeCard";

export const ManagerCard = () =>{
  const managerDetails = (empName) =>{
      alert (`Elon Musk is the manager of employee ${empName}`);
  }

  return <EmployeeCard managerHandler = {managerDetails}/>
}
//App.js
import { ManagerCard } from "./components/ManagerCard";

function App() {
  return <ManagerCard/>;
}

export default App;
⚠️ **GitHub.com Fallback** ⚠️