Looping
In a real-life situation you will of course need to deal with array's of data. Say we have an employee list:
const employees = [
{ id: 1, firstname: "John", lastname: "Doe", job: "Developer" },
{ id: 2, firstname: "Anna", lastname: "Tiger", job: "Developer" },
{ id: 2, firstname: "Jim", lastname: "Lion", job: "UX/UI" },
]
and we need to loop through this array to display a list of employees. We can achieve this in following manner:
const App = () => {
const employees = [
{ id: 1, firstname: "John", lastname: "Doe", job: "Developer" },
{ id: 2, firstname: "Anna", lastname: "Tiger", job: "Developer" },
{ id: 2, firstname: "Jim", lastname: "Lion", job: "UX/UI" },
]
return(
<div>
<h1>Employees</h1>
<ul>
{
employees.map( (person, index) => {
const name = `${ person.firstname } ${person.lastname }`
return(
<li key={ index.toString() }>{ name }</li>
)
})
}
</ul>
</div>
)
}
export default App
Breakdown
- As you can see on line 14, you can add code inside the HTML portion (enclosed by
{ }). - Line 15: The
.map()function loops through thedataarray, but needs a return because it actually returns a new array. - The
.map()function destructures the employees object into thepersonvariable and theindexis a "gift" from JavaScript :) - The
.map()function is similar to aforeachin C# or PHP, or Java
:::tip KEY
You can see here the use of the prop key on line 18 - this is
an internal React prop that you should use with items that
may occur more frequently (in this case the <li>) that key
acts as the "id" of the element, so to speak.
Although it is a "hard" requirement, and you need to include this key
in an array based element, React can function without it.
As soon as the content of the element needs to change for example,
the key is needed so React knows which item on the screen and in the
state needs to be updated.
:::
:::info Assignment Refactor the code so it implements components. Can you apply the Atomic Design principle? :::