First make sure you have the gatsby-source-filesystem, gatsby-transformer-sharp, and gatsby-plugin-sharp installed. Then check your gatsby-config.js file to make sure the plugins are getting loaded and configured directly. The relevant configuration is listed in the code below:
module.exports = {
plugins: [
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`,
},
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
],
}
We are now going to create a new page component to display a few images to look at how the Gatsby Image component works. Create a new file in the src/pages folder and call it gallery.js with the following code:
import React from "react";
import PropTypes from "prop-types";
import { graphql } from "gatsby";
import Img from "gatsby-image";
import Layout from "../components/layout";
import SEO from "../components/seo";
const Gallery = ({ data }) => (
<Layout>
<SEO title="Image gallery" />
<h1>Image Gallery</h1>
<Img fluid={data.astronautImage.childImageSharp.fluid} alt="Astronaut" />
<Img fixed={data.gatsbyIcon.childImageSharp.fixed} alt="Gatsby Icon" />
</Layout>
);
Gallery.propTypes = {
data: PropTypes.object.isRequired,
};
export const query = graphql`
{
gatsbyIcon: file(relativePath: { eq: "gatsby-icon.png" }) {
childImageSharp {
fixed(width: 512) {
...GatsbyImageSharpFixed
}
}
}
astronautImage: file(relativePath: { eq: "gatsby-astronaut.png" }) {
childImageSharp {
fluid(maxWidth: 1000) {
...GatsbyImageSharpFluid
}
}
}
}
`;
export default Gallery;
This will load one fixed sized image and one fluid sized image and display it on the page. If you go to the /gallery page you will see two images. Try resizing your browser to see how the images work. Hard refresh the page to see the images blur up when they are loading.
If you followed along with the last episode, you can change the GraphQL query for the field_image field in the articles.js file to:
relationships {
field_image {
localFile {
childImageSharp {
fluid(maxWidth: 600) {
...GatsbyImageSharpFluid
}
}
}
}
}
Then change the image prop being sent to the ArticlePreview component in that same file:
<ArticlePreview
key={article.id}
title={article.title}
path={article.path.alias}
image={article.relationships.field_image.localFile.childImageSharp.fluid}
alt={article.field_image.alt}
summary={article.body.summary ? article.body.summary : article.body.processed.substring(0, 300)}
/>
Now go to the articlePreview.js file, make sure you add the correct import statement at the top:
import Img from 'gatsby-image';
Then change the HTML image tag to the new Gatsby image component:
<Img fluid={image} alt={alt} />
You should be able to view your Articles listing page and see the blur up effect in action. You are now using the Gatsby Image component and processing plugins!