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, add an- onEditfunction that requires a- projectas a parameter and returns- void.- src\projects\ProjectCard.js...ProjectCard.propTypes = {project: PropTypes.instanceOf(Project).isRequired, //include this comma+ onEdit: PropTypes.func.isRequired};...
- Update the - handleEditClickevent to invoke the function passed into the- onEdit- propand remove the console.log statement.- src\projects\ProjectCard.jsfunction 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 to- ProjectListthat takes a- projectas an argument and logs it to the- console.
- Wire up the onEdit event of the - ProjectCardcomponent to the- handleEditevent handler.- In VS Code, the code snippet - nfncan help create the- handleEditevent 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"><ProjectCardproject={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.