reactjsgatsby

Component Not Rendering in .map Function


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?


Solution

  • 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.