0

I want to map my export in GraphQL, instead of repeat my images 3 times, check my code to understand me.

this is my export :

    export default [
  {
    id: Math.random(),
    imageUrl: require("../../images/recent-game/1.jpg"),

  },
  {
    id: Math.random(),
    imageUrl: require("../../images/recent-game/2.jpg"),

  },
  {
    id: Math.random(),
    imageUrl: require("../../images/recent-game/3.jpg"),

  },
]

This is my import and GraphQL

import BackgroundImage from "gatsby-background-image"
import { useStaticQuery, graphql } from "gatsby"
const getData = graphql`
  {
    image1: file(relativePath: { eq: "recent-game/1.jpg" }) {
      childImageSharp {
        fluid {
          ...GatsbyImageSharpFluid
        }
      }
    }
    image2: file(relativePath: { eq: "recent-game/2.jpg" }) {
      childImageSharp {
        fluid {
          ...GatsbyImageSharpFluid
        }
      }
    }
    image3: file(relativePath: { eq: "recent-game/3.jpg" }) {
      childImageSharp {
        fluid {
          ...GatsbyImageSharpFluid
        }
      }
    }

  }
`

Here i want to map my images instead of repeating them, depending on my export

Adam Kif
  • 107
  • 2
  • 9

1 Answers1

1

How about a reusable image component?

// Image
import React from 'react';
import { StaticQuery, graphql } from 'gatsby';
import Img from 'gatsby-image';

const Image = props => (
  <StaticQuery
    query={graphql`
      query {
        images: allFile {
          edges {
            node {
              relativePath
              name
              childImageSharp {
                fluid(maxWidth: 1000) {
                  ...GatsbyImageSharpFluid
                }
              }
            }
          }
        }
      }
    `}
    render={data => {
      const image = data.images.edges.find(n => {
        return n.node.relativePath.includes(props.filename);
      });
      if (!image) {
        return null;
      }

      // const imageSizes = image.node.childImageSharp.sizes; sizes={imageSizes}
      return <Img alt={props.alt} fluid={image.node.childImageSharp.fluid} />;
    }}
  />
);

export default Image;

And map components.

// Parent
{
  [
    { id: 0, filename: "gatsby-icon.png" },
    { id: 1, filename: "gatsby-icon.png" }
  ].map(item => {
    return (
      <div key={item.id}>
        <Image filename={item.filename} alt={String(item.id)} />
      </div>
    );
  });
}

You should check gatsby-source-filesystem of course.

lannex
  • 41
  • 6