reactjsarray-map

Map over an array in React


I am building an app that displays video games and various info about them, pulling data from an API. I am trying to display all of the platforms that the game is playable on, PlayStation, Xbox, etc. The JSON has an array of platforms for each game that each contain a platform object with a name (that I am trying to display). Maps really confuse me I would really appreciate someone's help with this. I will include a snippet of the JSON.

  "count": 1326,
  "next": "https://api.rawg.io/api/games?key=8d1a421af80b4f9b8650de12d9943010&page=2&search=destiny",
  "previous": null,
  "results": [
    {
      "slug": "destiny",
      "name": "Destiny",
      "playtime": 24,
      "platforms": [
        {
          "platform": {
            "id": 1,
            "name": "Xbox One",
            "slug": "xbox-one"
          }
        },
        {
          "platform": {
            "id": 18,
            "name": "PlayStation 4",
            "slug": "playstation4"
          }
        },
        {
          "platform": {
            "id": 14,
            "name": "Xbox 360",
            "slug": "xbox360"
          }
        },
        {
          "platform": {
            "id": 16,
            "name": "PlayStation 3",
            "slug": "playstation3"
          }
        }
      ],
const GameCard = ({
  game: {
    name,
    background_image,
    metacritic,
    released,
    platforms,
    platform,
    esrb_rating,
  },
}) => {
  return (
    <div className="bg-gray-600/30 m-5 p-0 rounded-xl shadow-xl shadow-gray-700 border-solid border-2 border-gray-700 max-w-[640px] hover:scale-105 ease-in duration-300">
      <img
        className="rounded-t-xl h-[360px] w-[640px] border-b-2 border-gray-600"
        alt={name}
        src={
          background_image
            ? background_image
            : "https://via.placeholder.com/640x360"
        }
      />
      <h1 className="text-center text-4xl text-gray-900 tracking-wide font-bold mt-2 font-mono">
        {name}
      </h1>
      <div className="text-gray-800 text-center font-mono py-2">
        {platforms ? platforms.map(() => <span></span>) : null}


Solution

  • Per W3Schools:

    map() creates a new array from calling a function for every array element.

    map() calls a function once for each element in an array.

    map() does not execute the function for empty elements.

    map() does not change the original array.

    This creates an array of names from an array of platform objects, such as results.platforms in the json snippet you showed.

    platforms.map(platform => <span>{platform.platform.name}</span>)