Skip to content

πŸ–₯️ 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.

If you need to, start the development server by running the following command in your terminal:

Terminal window
npm run dev

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 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.

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:

app/routes/_index.tsx
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!”:

Title as array

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?

app/routes/_index.tsx
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:

MyBrilliantArticles styled

With this knowledge in mind, let’s think how we can use the map function to dynamically render our list of games.

Let’s recap what we know so far:

  1. If we embed an array inside some JSX, React will automatically render the elements of this array straight out to the screen.
  2. 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;
});

Let’s see how we can use this to display a list of games.

app/routes/_index.tsx
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:

Unstyled game title list

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 test
  • some: returns true if at least one element in an array passes a test
  • every: returns true if all elements in an array pass a test
  • includes: returns true if an array contains a certain element
  • filter: returns a new array of elements that pass a certain test or condition
  • reduce: 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.