React list rendering
displaying content organized in an array of objects
Most of our React projects will involve:
fetching an array of data from a source
saving that data set into an array variable
listing that array's elements on the user interface
The map()
method
map()
methodThink 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:
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 arrya'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
In the above example, only the entry titles with "2025" would be listed.
Therefore, we can do a lot of filtering when we couple map
with conditional rendering!
Last updated