0

I'm trying to create card components and map through my data file to display them, which I managed to do with one array object data file. But my problem occurs if I want to reuse the card component with a new array data file, I can't seem to get the data.

So data example

 export const data1 = [
  {
   title: 'first',
   desc: 'first desc,
   img: 'image-1.jpg'
  },
  {
   title: 'second',
   desc: 'second desc,
   img: 'image-2.jpg'
  },
 ]

So if I only have one data array, I just map through it like this

 {data1.map((data, index) => {
  return (
 <Title>{data.title}</Title>
 <Desc>{data.desc}</Desc>
 <Img src={data.img} />
 )
 })

Then if I wanna display this card component, I would just add it to my page

 <CardComponent />

But now if I wanna reuse this component and just switch out the data, I can't map through it properly because it's only mapping through the data1 array.

So if I make another array

 export const dataTwo = [
  {
   title: 'third',
   desc: 'third desc,
   img: 'image-3.jpg'
  },
  {
   title: 'fourth',
   desc: 'fourth desc,
   img: 'image-4.jpg'
  },
 ]

Now I can't reuse my component because the map() is only targeting data1.map and not dataTwo.map

So I'm not sure exactly how I'd create essentially a new Card component

Ideally, I'd want this result

 <Navbar />
 <CardComponent {...data1} />
 <MainSection>
 <CardComponent {...dataTwo} />
 <Footer />

But the issue is I am mapping through the values instead of just getting data from a regular object, so this method doesn't work.

Any idea how I would implement this?

2 Answers 2

1

Simply pass the arrays as a prop to CardComponent, such as a data prop.

<CardComponent data={data1} />
...
<CardComponent data={dataTwo} />

And map the passed data prop in CardComponent. Remember that the mapping needs to return everything wrapped in a single node (i.e. div, Fragment, etc..) and should have an attached react key.

Example

const CardComponent = ({ data }) => {
  return (
    <>
      {data.map((data, index) => {
        return (
          <Fragment key={index}>
            <Title>{data.title}</Title>
            <Desc>{data.desc}</Desc>
            <Img src={data.img} />
          </Fragment>
        );
     })}
    </>
  );
};
Sign up to request clarification or add additional context in comments.

Comments

0

If you have multiple arrays that you want to be displayed, you can flatten them together into one when calling the component, eg:

<CardComponent data={data1.concat(dataTwo)} />
props.data.map((item) => (
    <Title>{item.title}</Title>
    <Desc>{item.desc}</Desc>
    <Img src={item.img} />
))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.