Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How display a Contentul image with Gatsby

I'm trying to display a single image which is stored on Contentful. This is my query to get the url and the title of the image :

contentfulAsset(title: {eq: "kevin"}) {
  file {
    url
    fileName
  }
}

I use the gatsby-image plugin but there is no explanation to know how to use this query to display a single image.

They only explain the situation with multiples images and a node...

{node.image[0].resolutions.src && (
  <Img
    style={{ margin: 0 }}
    resolutions={node.image[0].resolutions}
  />
)}
like image 676
Kévin Furet Avatar asked Apr 24 '18 17:04

Kévin Furet


1 Answers

My first advice would be to always use the GraphiQL page while developing. it gives you an idea on how to use the query results on your Components.

http://localhost:8000/___graphql

Your query depends on how you want to display your image.

Suppose that you have stored an image with the field name myImage on Asset content model on Contentful.

Display with HTML5 <img /> tag

If you want to use a simple <img /> tag

your query

contentfulAsset(title: { eq: "kevin"}}) {
  title
  file {
    url
  }
}

your component

// ...
const MyComponent = props => {
  const myImage = props.data.contentfulAsset;

  return <img src={myImage.file.url} alt={myImage.title} />
}

Display with gatsby-image plugin

If you want to take benefit of the gatsby-image plugin, you first need to know if you want to use the resolutions or sizes child on your query.

See gatsby-image documentation for more information.

Then you can use a query Fragment available with gatsby-source-contentful.

See https://www.gatsbyjs.org/packages/gatsby-image/#gatsby-source-contentful

your query

So let say we want to display a responsive image with a blur effect while loading, with Webp format:

contentfulAsset(title: { eq: "kevin"}}) {
  title
  sizes(quality: 100) {
    ...GatsbyContentfulSizes_withWebp
  }
}

Note: by default, the resolutions and sizes quality are set to 50. That's why I set it to 100 in this query

your component

const MyComponent = props => {
  const myImage = props.data.contentfulAsset;

  return <Img sizes={myImage.sizes} alt={myImage.title} />
}

Like most of official Gatsby plugins, you can find a very good example in the examples folder on the GitHub repository:

https://github.com/gatsbyjs/gatsby/tree/master/examples/using-contentful

like image 98
Nenu Avatar answered Sep 22 '22 01:09

Nenu