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