Lab 12: Hiding and Showing Components
Objectives
- Add state to a component
- Hide and show a component
Steps
Add state to a component
Add a state variable
projectBeingEdited
to hold which project is currently being edited. And updatehandleEdit
to set theprojectBeingEdited
variable.src\projects\ProjectList.tsx
- import React from 'react';+ import React, { useState } from 'react';import { Project } from './Project';import ProjectCard from './ProjectCard';import ProjectForm from './ProjectForm';interface ProjectListProps {projects: Project[];}function ProjectList({ projects }: ProjectListProps) {+ const [projectBeingEdited, setProjectBeingEdited] = useState({});const handleEdit = (project: Project) => {- console.log(project);+ setProjectBeingEdited(project);};return (...);}export default ProjectList;
Hide and show a component
Conditionally render the
ProjectForm
when the projectBeingEdited equals the current project in the list, otherwise display aProjectCard
.src\projects\ProjectList.tsx
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.