⚠️ This lesson is retired and might contain outdated information.

Process Images and Render them using GatsbyImage

Laurie Barth
InstructorLaurie Barth
Share this video with your friends

Social Share Links

Send Tweet

GatsbyImage is a React component specially designed to give users a great image experience. It combines speed and best practices.

Install gatsby-transformer-sharp. Source image files from your post frontmatter, process them using gatsby-plugin-sharp and query them using gatsby-transformer-sharp. Then proceed to use the GatsbyImage component exported from gatsby-plugin-image to render the processed images.

Note: GatsbyImage is designed to support three different layouts, fixed: the image is not responsive, fullWidth: the image is designed to display the full width of the screen and will stretch beyond the size of its source if necessary, and constrained: a responsive image that will get larger and smaller depending on the screen size but will not get larger than the size of the source image (or width/height if either is passed).

Instructor: [0:00] Change your posts so that they're inside the directory with their original filename and use index.mdx for the filename instead. This will ensure they're available at the same slug.

[0:13] Next, add an image to that directory that you'd like to use as the banner for your post. Inside the frontmatter of the post add image and point to a relative path to the image file. You also want to add an imageAlt.

[0:44] In order to query our transformed images, we're going to need to install gatsby-transformer-sharp. This will give us the API we need to use GraphQL to grab our images. Make sure to add gatsby-transformer-sharp to your gatsby-config file as well.

[1:07] Now we can query our images. In your mdx.slug file, query for image and imageAlt on the frontmatter. Image is a file node that can be processed using child ImageSharp. Grab Gatsby image data from it. You want to process this image using the constrained layout, so pass that as well. Import { GatsbyImage, getImage } from 'gatsby-plugin-image'.

[1:50] Next, create an image variable using the getImage function by passing post.frontmatter.image. This will do the traversal for you. In your GatsbyImage component, pass image as image and pass the alt as post.frontmatter.imageAlt.

[2:20] Now the image is available as a banner on both of your pages.