Lab 11: Communicating from Child to Parent Component
Objectives
- In a child component, accept a function as a prop and invoke it
- In a parent component, implement a function and pass it as a prop to a child component
Steps
In a child component, accept a function as a prop and invoke it
In the
Prop Typesdefinition at the bottom of the component file, add anonEditfunction that requires aprojectas a parameter.src\projects\ProjectCard.jsx...
ProjectCard.propTypes = {
project: PropTypes.instanceOf(Project).isRequired, //include this comma
+ onEdit: PropTypes.func.isRequired
};
...Update the
handleEditClickevent to invoke the function passed into theonEditpropand remove the console.log statement.src\projects\ProjectCard.jsxfunction ProjectCard(props) {
const { project,
+ onEdit
} = props;
const handleEditClick = (projectBeingEdited) => {
+ onEdit(projectBeingEdited);
- console.log(projectBeingEdited);
};
...
}
In a parent component, implement a function and pass it as a prop to a child component
Add a
handleEditevent handler toProjectListthat takes aprojectas an argument and logs it to theconsole.Wire up the onEdit event of the
ProjectCardcomponent to thehandleEditevent handler.In VS Code, the code snippet
nfncan help create thehandleEditevent handler.src\projects\ProjectList.jsx...
function ProjectList ({ projects }) {
+ const handleEdit = (project) => {
+ console.log(project);
+ };
const items = projects.map(project => (
<div key={project.id} className="cols-sm">
<ProjectCard
project={project}
+ onEdit={handleEdit}
></ProjectCard>
<ProjectForm></ProjectForm>
</div>
));
return <div className="row">{items}</div>;
}Verify the application is working by following these steps:
- Open the application in your browser and refresh the page.
- Open the
Chrome DevToolsto theconsole(F12orfn+F12on laptop). - Click the edit button for a project.
- Verify the project is logged to the
Chrome DevToolsconsole.

You may remember that logging was happening in a previous lab. In the previous lab, the logging was occuring in the child component. In this lab, we have removed the logging in the child component
ProjectCardand are invoking a method on the parent list componentProjectList. The allows the card component to be easily reused in another part of the application.