React how to render dynamic images inside nested data objects

Viewed 149

I can console.log() the data I want after mapping through my data from my GraphQL query. However, the nested .map functions are not rendering my JSX. Is it possible to render JSX in nested .maps?

const NikonGallery = ({ data }) => {
return (
<Layout>
{data.allFiles.nodes.map((item) => {
        Object.entries(item).map(([key, value]) => {
          value.map((image) => {
            console.log("Individual image", image) // Logs show the data I want
            return ( 
              <>
                <GatsbyImage
                  image={image.gatsbyImageData}
                  alt={image.description}
                />
              </>
            )
          })
        })
      })}
 </Layout>
 )
}

export default NikonGallery

The data from GraphQL/Contentful is a nested array of objects. I'm having trouble getting the JSX to render when I call the nested objects via .map.

1 Answers

Regarding the nested maps, you'll need to make some changes to return a proper expression from each map. The reason the console log works is because the code still loops; however, no expression is returned from the map for React to render. Try this:

data.allFiles.nodes.map((item) => {
    return Object.entries(item).map(([key, value]) => {
      return value.map((image) => {
        console.log("Individual image", image) // Logs show the data I want
        return ( 
          <>
            <GatsbyImage
              image={image.gatsbyImageData}
              alt={image.description}
            />
          </>
        )
      })
    })
  })}
</Layout>
)

When using the Gatsby image plugin for dynamic images such as this, you should use the getImage() method provided by the plugin. The import should look like this:

import { GatsbyImage, getImage } from "gatsby-plugin-image";

And the usage in your case would look something like this:

value.map((image) => {
        const gatsbyImage = getImage(image);
        return ( 
          <>
            <GatsbyImage
              image={gatsbyImage}
              alt={image.description}
            />
          </>
        )
      })
Related