Lab 6: Passing Data to a Component
Objectives
- Create a reusable list component
- Pass data into a component property
Steps
Create a reusable list component
Create the file
src\projects\ProjectList.js
Implement a
ProjectList
function component that meets the following specifications:- Takes a
projects
array as aprop
. - Displays the
projects
array as aJSON string
.
src\projects\ProjectList.js
import React from 'react';
import { Project } from './Project';
function ProjectList({ projects }) {
return <pre>{JSON.stringify(projects, null, ' ')}</pre>;
}
export default ProjectList;- Takes a
Define the property (prop) and its type using the
prop-types
library by doing the steps below.- Open a command prompt (Windows) or Terminal (Mac) in the
keep-track
directory, and run the following command to install theprop-types
library.npm install prop-types
- Add the following prop type definition.
src\projects\ProjectList.js
import React from 'react';
+ import PropTypes from 'prop-types';
+ import { Project } from './Project';
function ProjectList({ projects }) {
return <pre>{JSON.stringify(projects, null, ' ')}</pre>;
}
+ ProjectList.propTypes = {
+ projects: PropTypes.arrayOf(PropTypes.instanceOf(Project)).isRequired
+ };
export default ProjectList;- Open a command prompt (Windows) or Terminal (Mac) in the
Pass data into a component property
Modify
src\projects\ProjectsPage.js
to render theProjectList
component and pass it theMOCK_PROJECTS
array instead of directly displaying the data.src\projects\ProjectsPage.js
import React from 'react';
import { MOCK_PROJECTS } from './MockProjects';
+ import ProjectList from './ProjectList';
function ProjectsPage() {
return (
<>
<h1>Projects</h1>
- <pre>{JSON.stringify(MOCK_PROJECTS, null, ' ')}</pre>
+ <ProjectList projects={MOCK_PROJECTS} />
</>
);
}
export default ProjectsPage;Verify the application is displaying the projects as it was in the last lab.