Home > Net >  Mapping data in a JSX Component
Mapping data in a JSX Component

Time:08-03

I'm trying to render a Card component dynamically mapped from an array of objects. The issue is I'm getting an "unexpected token error ..." And URL won't render. I should see five cards display based on the data inside the array, but it throws an error. Does anyone see where I'm going wrong? I'm using React 18 if that matters.

Component code:

import React from "react";
import links from "../links";

function Card (props) {
  return (
    <div>
      <div className="link-container">
        <div className="row">
          <div className="card">
            <hr className="divide"></hr>
            <img className="img" src={props.img} alt="social-icon" />
            <h4>{props.name}</h4>
          </div>
        </div>
      </div>
    </div>
  )
}

Data:

  const links = [
    {
        id: 1,
        name: "Youtube",
        img:"./img/youtube.svg",
        href: "https://www.youtube.com/c/SubwaySounds"
    },
    {
        id: 2,
        name: "Spotify",
        img:"./img/spotify.svg",
        href: "https://artists.spotify.com/c/artist/3DM32kjsG7Pp5EM7o3Uv7t/profile/overview"
    },
    {
        id: 3,
        name: "Tiktok",
        img:"./img/tiktok.svg",
        href: "https://www.tiktok.com/@nysubwaysounds"
    },
    {
        id: 4,
        name: "Instagram",
        img:"./img/instagram.svg",
        href: "https://www.instagram.com/nycsubwaysounds/?hl=en"
    },
    {
        id: 5,
        name: "Shop",
        img:"./img/shop.svg",
        href: "https://my-store-11524143.creator-spring.com/"
    }
]

export default links;

App.jsx:

 import Header from "./Header";
 import Card from  "./Card";
 import links from "../links";
    
 function CreateCard (socialLinks) {
   return (
     <Cards
       key= {socialLinks.id}
       img= {socialLinks.img}
       name= {socialLinks.name}
       href= {socialLinks.href}
    />
   )
  }
    
  function App() {
    return (
      <div>
        <Header />
        <Card {links.map(createCard)} />
      </div>
    );
  }
    
  export default App;

CodePudding user response:

use the React map method

function App() {
  return (
    <div>
      <Header />
      {
        links.map((link, linkKey) => (
          <Card
            key={linkKey}
            img= {socialLinks.img}
            name= {socialLinks.name}
            href= {socialLinks.href}
          />
        ))
      }
    </div>
  );
}

  • Related