Search code examples
javascriptreactjsrendering

Why wont my data render onto my card component when using spread operator?


I am trying to render data from a data file onto my card component by destructuring an object and using the spread operator (apologies if my jargon is wrong I don't know the exact words to describe it). I have done this in a project previously and tried to copy how I did it but the data will not render - get no issues in the console either.

I have made a code sandbox for it here - you will want to open it in a new window to see the card component in action as I have not made a responsive layout yet so it wont render on smaller screens.

The important files relevant to this are:

  • PortfolioCardData.js (stores the data which is exported)
  • PortfolioPageHero.js (where the AnimatedCard is rendered and I spread the data as an object into the card)
  • AnimatedCard.js & AnimatedCardDetails.js - where I destructure an object in the functions parenthesis and then use objects to place where the title, image etc will go

Solution

  • The issue is in the file PortfolioPageHero.js where you are passing data by destructuring to

    <AnimatedCard {...PortfolioCardData1}/>
    

    where PortfolioCardDetails1 is an array of objects

    export const PortfolioCardData1 = [
        {
            key: 2,
            image: "",
            title: "Recipe App",
            subtitle: "Built with React | Mobile First",
            buttonText: "Take a look"
        }
    ]
    

    so when you use spread operator on array to pass the data then that array is passed as a key-value pair of index : valueAtIndex somthing like this

     "0": {
        key: 1,
        image: "",
        title: "Ecommerce",
        subtitle: "Built with react | Redux | Stripe",
        buttonText: "Take a look"
      }
    

    so, you can access this data by doing props.0.image , etc or you can spread the object while destructuring like this

    <AnimatedCard {...PortfolioCardData1[0]}/>
    

    then your current code would work.