Search code examples
javascriptreactjsgraphqlgatsbynetlify-cms

Component props to GraphQL


I am building a simple web application using React and GatsbyJS, and I use NetlifyCMS to manage the content. Using gatsby-transformer-remark I load data containing path to the images I would like to load using gatsby-transformer-sharp.

So, I've created a Image component that recieves the path to its props:

<Image path={post.frontmatter.thumbnail} />

I want this component to get the path, ask for an gatsby-transformer-sharp node with GraphQL and then use the returned data in the gatsby-img component.

I am very new to both React and GatsbyJS, so obviously my solution doesn't work.

import React from 'react';
import Img from 'gatsby-image';

export default class Image extends React.Component {
  render() {
    return(
      <Img
        sizes={this.props.file.childImageSharp.sizes}
      />
    );
  }
}

export const getSizesQuery = graphql`
  query GatsbyImageSampleQuery($path: this.props.path) {
      file(relativePath: { eq: $path }) {
        childImageSharp {
          sizes {
            base64
            tracedSVG
            aspectRatio
            src
            srcSet
            srcWebp
            srcSetWebp
            sizes
            originalImg
            originalName
          }
        }
      }
    }
`;

What's the right way to do this?


Solution

  • Gatsby pulls all of your data into its internal nodes system, then pushes data into your components only via queries in either layouts or pages.

    This single source of entry ensure that Gatsby can compile all your data to static JSON. The approach provided by @toufek-khoury will deliver data to your component, but it will bypass the Gatsby cache. In almost every case, you want your data to be cached, that's what makes Gatsby so unbelievably fast.

    The solution is to fetch all the data you need for a page in the pageQuery.