0

I'm trying to iterate an array of data into a component. The way I'm doing it looks like this

<article className={styles.contentList}>
    {
        organizations.map((item, index) =>{
            return <OrganizationCard data={item} key={index} />
        })
    }
</article>

So far my <OrganizationCard /> looks like this

export const OrganizationCard = (data, key)=>{
    console.log(data);
    <article className={styles.mainContainer}>
        <p>organization</p>
    </article>
}

When I console.log the organizations data in the parent component I get an array of all the data so I know it's there. As you can see I even console.log() the data prop inside my <OrganizationCard /> which also shows the data is being passed in. However, in the browser nothing iterates. When I look at the elements tab at the .contentList article there's nothing being rendered. Seeing that I've done this several times in regular React projects the only thing I could think of trying to add () to the return so it's return(<OrganizationCard />) which gave the same exact results. Does anybody know why this might be happening and how to fix the issue?

4
  • 2
    You should return from OrganizationCard component as well. Commented Jul 3, 2024 at 6:15
  • oh.... duh, I don't know how I didn't see that I didn't do that lol. Commented Jul 3, 2024 at 6:17
  • 2
    Your OrganizationCard component is wrong. The signature is wrong: you get props and need to extract the data prop, either by deconstruction or by dot notation; and you don't ever get the key in the props, that's handled react-internal. Your return is wrong: currently you return nothing, you just create a virtual dom node and let it garbage collect. Commented Jul 3, 2024 at 6:18
  • the key for OrganizationCard should be an ID or any other unique value that belongs to the object (like item.id) that is constant among re-renders. index of map function makes all the cards to re-render whenever a new card is added or removed. Commented Jul 3, 2024 at 7:11

1 Answer 1

2

Add a return statement to your <OrganizationCard /> component. Like this:

export const OrganizationCard = (data)=>{
 // desctructure data props
 const { name } = data; // as an example

 console.log(data);
 return (
    <article className={styles.mainContainer}>
        <p>organization - {name}</p>
    </article>
 ) 
}

By the way, you are already adding the key prop to your parent component. In my opinion, it is not necessary to add it in the child one as well. It is just duplication. And, it is better not to be the index but a unique id.

Sign up to request clarification or add additional context in comments.

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.