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}
/>
)}
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.
<img />
tagIf you want to use a simple <img />
tag
contentfulAsset(title: { eq: "kevin"}}) {
title
file {
url
}
}
// ...
const MyComponent = props => {
const myImage = props.data.contentfulAsset;
return <img src={myImage.file.url} alt={myImage.title} />
}
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
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
andsizes
quality are set to 50. That's why I set it to 100 in this query
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With