π₯οΈ Displaying data with `map`
In our previous step, we fetched a list of games from the database and displayed them on the page.
In this step, we will start by displaying the game titles on the page.
Start the development server
Section titled βStart the development serverβIf you need to, start the development server by running the following command in your terminal:
npm run dev
Data in React
Section titled βData in ReactβLook again at the shape of the data we fetched in the previous step:
games: [ { id: 'cm7s2xqfx0000xiv0eig2y3va', title: 'The Legend of Zelda: Breath of the Wild', description: 'An open-world adventure game set in the kingdom of Hyrule.', price: 59.99, rating: 4.9, releaseDate: '2017-03-03T00:00:00.000Z', createdAt: '2025-03-02T20:24:32.541Z', updatedAt: '2025-03-02T20:24:32.541Z' }, { id: 'cm7s2xqg00001xiv0adp4zac7', title: 'The Witcher 3: Wild Hunt', description: 'An action RPG set in a fantasy world full of monsters and magic.', price: 39.99, rating: 4.8, releaseDate: '2015-05-19T00:00:00.000Z', createdAt: '2025-03-02T20:24:32.545Z', updatedAt: '2025-03-02T20:24:32.545Z' }, // ... more games here...]
Notice the square brackets []
around the object? This means that games
is an array of objects.
We need some way to take each of these objects and display their properties on the page.
But how? π€
The map
function
Section titled βThe map functionβThe map
function in JavaScript allows us to loop through an array and apply a function to each element, returning a new array with the results.
Now that we understand how the map
function works, letβs see how we can use it in React to display a list of items.
Rendering arrays in React components
Section titled βRendering arrays in React componentsβIt turns out that React automatically renders the content of an array directly to the screen when used in JSX.
We can see this if we replace the main page title with an array of strings:
19 collapsed lines
import { PrismaClient } from '@prisma/client'import { json } from '@remix-run/node'import { useLoaderData } from '@remix-run/react'import type { MetaFunction } from "@remix-run/node";
export const meta: MetaFunction = () => { return [ { title: "New Remix App" }, { name: "description", content: "Welcome to Remix!" }, ];};
export async function loader() { const prisma = new PrismaClient()
const games = await prisma.game.findMany()
return json({ games })}
export default function Index() { const { games } = useLoaderData<typeof loader>()
console.log({ games })
return ( <div className="flex items-center justify-center min-h-screen"> <h1 className="text-4xl font-bold">{["Hello", "World!"]}</h1> </div> );}
If you check the browser, you will see that the page title is now βHelloWorld!β:
Arrays of React components
Section titled βArrays of React componentsβIf we take this a step further, what do you think will happen if we replace the plain strings inside this array with full React components?
export default function Index() { const { games } = useLoaderData<typeof loader>()
console.log({ games })
return ( <div className="flex items-center justify-center min-h-screen"> <h1 className="text-4xl font-bold">{["Hello", "World!"]}</h1> <h1 className="text-4xl font-bold"> {[ <span key="1" className="border border-red-500 p-2 text-red-500"> Hello </span>, <span key="2" className="border border-green-500 p-2 text-green-500"> World! </span> ]} </h1> </div> );}
Head back to your browser, and you should see the page title has changed again:
With this knowledge in mind, letβs think how we can use the map
function to dynamically render our list of games
.
If you were following the previous steps and altering code, make sure to revert your page title back to its original state before continuing.
(Unless you like the new look, of course! π)
Using map
to loop through an array of items
Section titled βUsing map to loop through an array of itemsβLetβs recap what we know so far:
- If we embed an array inside some JSX, React will automatically render the elements of this array straight out to the screen.
- The
map
function produces a new array from an existing one by applying a callback function to each element, e.g.
const doubledNumbers = numbers.map((number) => { return number * 2;});
π‘
This means that we can use the map
function to loop through an array of objects (like our games
array) and return a new array of components.
Letβs see how we can use this to display a list of games.
export default function Index() { const { games } = useLoaderData<typeof loader>();
console.log({ games });
return ( <div className="flex items-center justify-center min-h-screen"> <div> <h1 className="text-4xl font-bold">Hello, World!</h1> {games.map((game) => ( <div key={game.id}> <h2>{game.title}</h2> </div> ))} </div> </div> );}
Save the changes to your file and check the browser. You should see that the game titles are now displayed on screen:
Summary
Section titled βSummaryβIn this step, we learned how to use the map
function to loop through an array of items and display a list of game titles from our database.
There are many more JavaScript array functions that can be used to manipulate arrays in different ways. Below are a few examples for you to research further and experiment with:
find
: returns the first element that passes a testsome
: returnstrue
if at least one element in an array passes a testevery
: returnstrue
if all elements in an array pass a testincludes
: returnstrue
if an array contains a certain elementfilter
: returns a new array of elements that pass a certain test or conditionreduce
: reduces an array to a single value
Kent C. Dodds has a great game on JavaScript to know for React that demonstrates these methods in action.
- Display the price of each game along with its title.
- Make sure each price contains a
Β£
sign before it.