React list rendering
With many React projects, we usually render lists with data that we had previously:
- fetched from an external source
- saved into an array variable
To render the lists, we can make use of JavaScript's built-in map method!
The map method
Think of a blog entries in a database. Using whatever fetch method, we would have all those blog entries put into a variable as array elements. To display the blog entries on the user interface, we would simply use JavaScript's built-in map
function:
function App() {
const someData = [
"2020-01-01 : Happy New Year!",
"2019-12-31 : 2019 in review",
"2019-12-30 : What did we learn this year?",
"2019-12-29 : Looking forward to the 2020s!"
]
return (
<ul>
{ someData.map( (entry, index) =>
<li key={`${entry}-${index}`}>{entry}</li>
)}
</ul>
)
}
To review, a map
function passes each element of an array as an argument. In the case above, each element of the someData array looks like the title of a blog entry. The map
function then returns the HTML-like JSX necessary to display a list item that shows the blog entry's title. It does this until it displays all the array's elements.
Also, let's take note of the key
property, which helps React differentiate one list item from the others. The value makes use of the optional index
variable from the map
function, to give each list item its own unique identifier.
Conditional list rendering
We can also display only part of the array based on conditions:
function App() {
const someData = [
"2020-01-01 : Happy New Year",
"2019-12-31 : 2019 in review",
"2019-12-30 : What did we learn this year?",
"2019-12-29 : Looking ahead to the 2020s!"
]
return (
<ul>
{ someData.map( (entry, index) =>
{ entry.includes("2020") &&
<li key={`${entry}-${index}`}>{entry}</li>
}
)}
</ul>
)
}
In the above, we made use of the includes
method as well as the logical AND (&&
) to show only elements (entries) with 2020
in the, (i.e. only the first one.