Step 8
Let's update the Output.js
to dynamically render the sleep cycles:
function Output() {
const cycles = [
"11:44 PM",
"1:14 AM",
"2:44 AM",
"4:14 AM",
"5:44 AM",
"7:14 AM",
];
return (
<div>
<p>It takes the average human fourteen minutes to fall asleep.</p>
<p>
If you head to bed right now, you should try to wake up at one of the
following times:
</p>
<ul>
{cycles.map((cycle) => (
<li>{cycle}</li>
))}
</ul>
<p>A good night's sleep consists of 5-6 complete sleep cycles.</p>
</div>
);
}
export default Output;
Save the file and see the output:
Notice the cycles are displayed in an unordered list. I've made this change so we can work with a slightly more complex JSX syntax:
<ul>
{cycles.map((cycle) => (
<li>{cycle}</li>
))}
</ul>
When we mix JavaScript with HTML in JSX, we must put the JavaScript bits in
{}
.
Open the Developer Tool in the browser and notice a warning printed to the terminal:
The warning says, each child in a list must have a unique key. The key helps React to track changes in the child elements, as the state changes in the app. Here is a simple fix:
<ul>
{cycles.map((cycle, index) => (
<li key={index}>{cycle}</li>
))}
</ul>
JSX may feel strange and you may be confused when first starting using it. In my experience though, you will quickly get the hang of it, and then it will increase your coding productivity.