Optimizing Images with Gatsby Image

14 August 2020


Fleurs De Majorelle


Gatsby Image is a react component designed to optimize image loading times for static sites. It lazy-loads the images with a blur-up effect, which speeds up initial page loading times and holds the image position.

1) Install the gatsby default boilerplate using the Gatsby Cli, containing all the main configuration files to get you up and running quickly and install the following packages which allow you to process the images and use GraphQL queries to access images.

npm install --save gatsby-cli

gatsby new my-default-starter https://github.com/gatsbyjs/gatsby-starter default

npm install --save gatsby-image

npm install --save gatsby-transformer-sharp gatsby-plugin-sharp gatsby-source-filesystem

2)
The starter will have generated a gatsby config file. Here you must add the plugins if they are not there already. The gatsby source filesystem will by default contain a path to the images folder which can be changed if you move the images locally.

plugins: [

{

resolve: `gatsby-source-filesystem`,

options: { name: `images`,

path: `${__dirname}/src/images`,

},

},

`gatsby-transformer-sharp`,

`gatsby-plugin-sharp`

, ...additionalplugins

]

3) Add some images to the /src/images folder to test. Fire up the development server http://localhost:8000/ and the GraphiQL playground http://localhost:8000/___graphql to write your query.

gatsby develop

Example query:

GraphQl query



4) Copy the query and for this example we'll use it in the src/pages/index.js homepage. Replace fluid/src with the query fragment ...GatsbyImageSharpFluid.

export const data = graphql`

query MyQuery {

file(relativePath: { eq: "flora.jpg" }) {

childImageSharp {

fluid(maxWidth: 1000) {

...GatsbyImageSharpFluid

}}}}`

5) Import img from gatsby-image and add the img tag as below. You can destructure the query from props.

<Img fluid={props.data.file.childImageSharp.fluid} />

Full Component:

import React from "react"

import { graphql } from "gatsby"

import Layout from "../components/layout"

import SEO from "../components/seo"

import Img from "gatsby-image"

import "./index.css"


const IndexPage = props => (

<Layout>

<SEO title="Home" />

<Img fluid={props.data.file.childImageSharp.fluid} />

<article>

<h1>Fleurs De Majorelle</h1>

<p>Designers of high quality, bespoke floral creations, traditional or contemporary in design, arranged to suit your budget.</p>

</article>

</Layout>

)
export default IndexPage


export const data = graphql`

query MyQuery {

file(relativePath: { eq: "flora.jpg" }) {

childImageSharp {

fluid(maxWidth: 1000) {

...GatsbyImageSharpFluid

}}}}`

Made with ❤ © 2020 - Anisa Patel.

Built with GatsbyJS, React and GraphQL. The source code can be found on Github.