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 Types
definition, add anonEdit
function that requires aproject
as a parameter and returnsvoid
.src\projects\ProjectCard.js
...
ProjectCard.propTypes = {
project: PropTypes.instanceOf(Project).isRequired, //include this comma
+ onEdit: PropTypes.func.isRequired
};
...Update the
handleEditClick
event to invoke the function passed into theonEdit
prop
and remove the console.log statement.src\projects\ProjectCard.js
function 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
handleEdit
event handler toProjectList
that takes aproject
as an argument and logs it to theconsole
.Wire up the onEdit event of the
ProjectCard
component to thehandleEdit
event handler.In VS Code, the code snippet
nfn
can help create thehandleEdit
event handler.src\projects\ProjectList.js
...
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 DevTools
to theconsole
(F12
orfn+F12
on laptop). - Click the edit button for a project.
- Verify the project is logged to the
Chrome DevTools
console
.
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
ProjectCard
and are invoking a method on the parent list componentProjectList
. The allows the card component to be easily reused in another part of the application.