- Add state to a component
- Hide and show a component
-
Add a state variable
projectBeingEdited
to hold which project is currently being edited. And updatehandleEdit
to set theprojectBeingEdited
variable.- import React from 'react'; + import React, { useState } from 'react'; import { Project } from './Project'; import ProjectCard from './ProjectCard'; import ProjectForm from './ProjectForm'; function ProjectList({ projects }) { + const [projectBeingEdited, setProjectBeingEdited] = useState({}); const handleEdit = (project) => { - console.log(project); + setProjectBeingEdited(project); }; return ( ... ); } ... export default ProjectList;
-
Conditionally render the
ProjectForm
when the projectBeingEdited equals the current project in the list, otherwise display aProjectCard
.
...
function ProjectList({ projects }) {
const [projectBeingEdited, setProjectBeingEdited] = useState({});
const handleEdit = (project) => {
setProjectBeingEdited(project);
};
return (
<div className="row">
{projects.map((project) => (
<div key={project.id} className="cols-sm">
- <ProjectCard project={project} onEdit={handleEdit} />
- <ProjectForm />
+ {project === projectBeingEdited ? (
+ <ProjectForm />
+ ) : (
+ <ProjectCard project={project} onEdit={handleEdit} />
+ )}
</div>
))}
</div>
);
}
...
export default ProjectList;
-
Verify the application is working by following these steps:
-
Open the application in your browser and refresh the page.
-
Click the edit button for a project.
-
Verify the
<ProjectCard />
is removed and replaced by the<ProjectForm/>
.The
<ProjectForm/>
will be empty at this point. We will fill in the data in a future lab.You can do click another edit button on another
ProjectCard
and that card will change to a form. At this point, you may notice that the cancel button doesn't work. We will get that working in the next lab.
-