The goal of this step is to practice transforming lists of data into lists of components which can be included in JSX. As a result, we'll convert the EmailList
component from statically rendering the three EmailListItem
components to dynamically rendering an arbitrary list of EmailListItem
components. We'll also make use of more advanced prop types.
As always, if you run into trouble with the tasks or exercises, you can take a peek at the final source code.
Pull out the raw data that makes up the three EmailListItem
components into an EMAILS
const
array. Use Array.prototype.map
to convert the array of data into an array of components:
const EMAILS = [
{
id: 1,
from: '[email protected]',
subject: 'Mauris lacinia sapien quis libero.'
},
{
id: 2,
from: '[email protected]',
subject: 'Mauris ullamcorper purus sit amet nulla.'
},
{
id: 3,
from: '[email protected]',
subject: 'Suspendisse potenti.'
}
];
export default class EmailList extends PureComponent {
render() {
let emailComponents = EMAILS.map((email) =>
<li key={email.id}>
<EmailListItem from={email.from} subject={email.subject} />
</li>
);
return (
<ul className="email-list">
{emailComponents}
</ul>
);
}
}
Update EmailListItem
to take a single email
prop instead of individual props for each email property (don't forget the propTypes
!):
export default class EmailListItem extends PureComponent {
static propTypes = {
email: PropTypes.shape({
from: PropTypes.string.isRequired,
subject: PropTypes.string.isRequired
}).isRequired
};
render() {
let {email: {from, subject}} = this.props;
return (
<div className="email-list-item">
<span>{from}</span>
<span>{subject}</span>
</div>
);
}
}
The EmailList
component will need to be updated to pass the email
prop to EmailListItem
.
- Move the
EMAILS
out ofEmailList
into the top-levelApp
- Pass
EMAILS
inApp
as theemails
prop to<EmailList>
- Declare a new
emails
prop type usingPropTypes.arrayOf()
inEmailList
(you can share common prop types withEmailListItem
in aconstants.js
file) - Use
this.props.emails
in themap()
withinrender()
ofEmailList
Go to Step 4 - Fetch.