Design+Code logo

Quick links

Suggested search

Installation

Using the gatsby-plugin-image package requires installing a few packages. First, we need to install gatsby-plugin-image and gatsby-plugin-sharp.

npm install gatsby-plugin-image gatsby-plugin-sharp

If you plan on only using static images (images saved in your repository), install the gatsby-source-filesystem plugin as well.

npm install gatsby-source-filesystem

If you also want to use dynamic images (for example, images fetched from a content management system, meaning that images might change from time to time), install the gatsby-transformer-sharp plugin.

npm install gatsby-transformer-sharp

Next, we'll need to add the plugins in our gatsby-config.js file. Note that these might have already been added to the plugins array in gatsby-config.js , if you built your Gatsby project from a template like gatsby-starter-default.

// gatsby-config.js

module.exports = {
  plugins: [
    `gatsby-plugin-image`,
    `gatsby-plugin-sharp`,
    `gatsby-source-filesystem`, // If you need static images
    `gatsby-transformer-sharp`, // If you need dynamic images
  ],
}

StaticImage or GatsbyImage

The plugins we just installed include two different components that we can use to render images. One is called StaticImage , and one is GatsbyImage. StaticImage , as the name implies, is for static images, meaning that the images will always stay the same anytime this component will be rendered. For example, an image saved in your repository will always stay the same when rendered. Therefore, we would use the StaticImage component in this case. Note that the video of this section will only cover the StaticImage component. GatsbyImage , on the contrary, is used when the image changes. For example, when you reuse a same component but pass a different image every time, or when the image is coming from a content management system, GatsbyImage should be used.

Using StaticImage

First, add your image to your repository, or simply get a URL of an image hosted on the web. I have an image of a sleeping kitten, so I'll just add it to the src > images folder.

Gatsby Plugin Image image 1 In IndexPage.js - or any component where you want to use StaticImage , and let's import StaticImage from gatsby-plugin-image.

// IndexPage.js

import { StaticImage } from "gatsby-plugin-image"

In the return body, we'll just call the StaticImage and pass the src and alt attributes, just like the img HTML tag. If you didn't add the image to your repo and want to take an image URL, instead of passing the local path to the src attribute, pass your URL.

// IndexPage.js

<StaticImage src="../images/sleeping-kitten.jpg" alt="Sleeping kitten" />

Using GatsbyImage

To display a dynamic image with GatsbyImage, we'll first need to query our image with GraphQL. A typical GraphQL query looks like this one below. Each image fetched with GraphQL will have the childImageSharp field, in which you can set the gatsbyImageData.

query {
 blogPost(id: { eq: $Id }) {
   title
   body
   image {
     childImageSharp {
       gatsbyImageData(width: 200)
     }
   }
 }
}

Between the parentheses of gatsbyImageData, you can pass properties to style your image. See the Styling the image section below to learn more about the different options offered. Once the styling is satisfactory, import GatsbyImage and the getImage from gatsby-plugin-image.

import { GatsbyImage, getImage } from "gatsby-plugin-image"

In your component, get the image from the graphQL query with the getImage function.

import { GatsbyImage, getImage } from "gatsby-plugin-image"

const MyComponent = ({ data }) => { // data is fetched from GraphQL and passed to this component
	const image = getImage(data.blogPost.image)

	return (<div>
		{/* Content of MyComponent... */}
	</div>)
}

export const MyComponent

Use the GatsbyImage component to display your image.

import { GatsbyImage, getImage } from "gatsby-plugin-image"

const MyComponent = ({ data }) => {
	const image = getImage(data.blogPost.image)

	return (<div>
		<GatsbyImage image={image} alt={data.blogPost.title}/>
	</div>)
}

export const MyComponent

Styling the image

Next it's time to add some styling and a placeholder to our image! Below, the first value provided (in camelCase) for each property is for the StaticImage component, and the value in parentheses (in SCREAMINGSNAKECASE) is for the GatsbyImage component. The example code provided below are all for StaticImage. For StaticImage , we pass the properties as JSX attributes.

<StaticImage src="../images/sleeping-kitten.jpg" alt="Sleeping kitten" layout="fixed" width={400} aspectRatio={3 / 4} formats={["auto", "jpeg"]} />

And for GatsbyImage , we pass it as arguments to the gatsbyImageData resolver.

query {
 blogPost(id: { eq: $Id }) {
   title
   body
   image {
     childImageSharp {
       gatsbyImageData(
         width: 200
         placeholder: BLURRED
         formats: [AUTO, WEBP, AVIF]
       )
     }
   }
 }
}

First, we have the layout property, which determines the size of the image and the resizing behaviour. Three options are available for this property.

  • constrained (__CONSTRAINED __for GatsbyImage) - always keeps the aspect ratio of the original image. If the original image width is higher than the screen size, it'll scale down the image, with the same aspect ratio. This is the default value for layout.
  • fixed (FIXED) - the size of the image will always stay the same. It'll either be the original size of the image or the size set with the width and height properties.
  • fullWidth (FULL_WIDTH) - always displays the image at full width. Best used for banners and hero images. You can compare the three options by watching this short video.
<StaticImage src="../images/sleeping-kitten.jpg" alt="Sleeping kitten" layout="fixed" />

If the layout is set to constrained or fixed , we can adjust the width and height properties of our image. It accepts any number as value. If these values don't respect the original image's aspect ratio, the image will be cropped, and not stretched.

<StaticImage src="../images/sleeping-kitten.jpg" alt="Sleeping kitten" layout="fixed" width={400} height={400} />

The aspectRatio property can also be set. It accepts any fraction as a value, and the resulting image will be cropped. If you pass the aspectRatio property, only set a width or a height - and not both of them. gatsby-plugin-image will calculate the size depending on the aspect ratio provided.

<StaticImage src="../images/sleeping-kitten.jpg" alt="Sleeping kitten" layout="fixed" width={400} aspectRatio={3 / 4} />

Next up, we have our placeholder , which is what the user sees while the image is being loaded. Four options are available to you:

  • dominantColor (DOMINANT_COLOR for GatsbyImage) - the dominant color of the image will fill the placeholder image as a solid background color. This is the default value for placeholder.
  • blurred (BLURRED) - the user will see a blurred version of the image
  • tracedSVG (TRACED_SVG)- a simple SVG version of the image will be generated, and works best with simple shapes
  • none (NONE)- there's no placeholder while the image is being loaded We can also set the output formats of the generated image. It accepts an array of output formats. By default, it's set to ["auto", "webp"] (or [AUTO, WEBP] for GatsbyImage).
<StaticImage src="../images/sleeping-kitten.jpg" alt="Sleeping kitten" formats={["auto", "jpeg"]} />

Finally, we have some transformOptions to style our image even further. These are some advanced techniques, and most people don't need them. If you wish to transform your image, use the transformOptions property and set any option you wish that are in this list.

Learn with videos and source files. Available to Pro subscribers only.

Purchase includes access to 50+ courses, 320+ premium tutorials, 300+ hours of videos, source files and certificates.

BACK TO

Gatsby Cloud

READ NEXT

useOnClickOutside Hook

Templates and source code

Download source files

Download the videos and assets to refer and learn offline without interuption.

check

Design template

check

Source code for all sections

check

Video files, ePub and subtitles

react-hooks-handbook-gatsby-plugin-image

1

Intro to React Hooks

An overview of React Hooks and the frameworks you can use to build your React application blazingly fast

3:39

2

Create your first React app

Create your first React project from the Terminal and save it on your local computer

4:23

3

React Component

Create your first JSX component using React

2:54

4

Styling in React

How to style your React components using inline styling, separate stylesheets or styled-components

5:06

5

Styles and Props

Render different styles depending on different properties passed to your component

2:22

6

Understanding Hooks

Learn about the basics of React Hooks, which introduced at React Conf 2018

3:21

7

useState Hook

Use the useState hook to manage local state in your React component

2:54

8

useEffect Hook

Manage with your component's lifecycle with the useEffect hook

3:41

9

useRef Hook

Learn about the useRef hook, which replaces the JavaScript getElementById way

3:00

10

Props

Learn about props in React to pass data from parent to child components

3:11

11

Conditional Rendering

Render different UIs depending on different conditions and states

4:21

12

Load Local Data

Load local JSON data into your React application

4:04

13

Fetch Data from an API

Learn the basics of asynchronous functions and promises by fetching data from an API using fetch, useEffect and useState

5:40

14

Toggle a state

Learn how to toggle a state from true to false and back again

4:05

15

useInput Hook

Create a hook to get the value and the onChange event of input fields

6:04

16

Gatsby and React

Create a static content-oriented website using React on Gatsby

6:44

17

NextJS and React

Create your first NextJS React application

5:24

18

React TypeScript Part 1

Learn how to create a React TypeScript application using the Create React App, Gatsby and NextJS methods

8:19

19

React TypeScript Part 2

Learn the basics of TypeScript and how to use TypeScript in a React component

7:35

20

useScrollPosition Hook

Create a custom hook to listen to the current window position of the user

4:26

21

useOnScreen hook

Create a custom hook to listen to when an element is visible on screen

8:08

22

useContext Hook

Manage global states throughout the entire application

8:32

23

Fragments

Group multiple children together with React Fragments

2:43

24

Lazy Loading

Lazy Load heavy components to improve performance

4:05

25

React Suspense

Wait for data with React Suspense and React.lazy

3:13

26

Environment Variables

Make environment variables secret with a .env file

4:43

27

Reach Router

Create a multiple-pages React application with Reach Router

5:31

28

URL Params

Create unique URL with URL Params

4:04

29

SEO and Metadata

Optimize a React application for search engines with React Helmet

6:47

30

Favicon

Add an icon to a React website

3:03

31

Dynamic Favicon

Change the favicon's fill color depending on the user's system appearance

2:14

32

PropTypes

Implement props type-checking with PropTypes

3:54

33

Custom PropTypes

Create a custom PropType using a validator function

3:58

34

useMemo Hook

Prevent unnecessary re-renders when the component stays the same

4:05

35

forwardRef Hook

Forward a ref to a child component

3:28

36

Handling Events

How to handle events in React

5:44

37

Spread attributes

Learn how to make use of the spread operator

3:35

38

useMousePosition Hook

Detect the user's mouse position on a bound element

4:55

39

useReducer with useContext Part 1

Create a reducer to be used in a context

7:33

40

useReducer with useContext Part 2

Incorporate useReducer with useContext

6:48

41

useReducer with useContext Part 3

Connect the context and reducer with the frontend

5:43

42

Netlify

Deploy to production using Netlify

5:08

43

Gatsby Cloud

Deploy to production using Gatsby Cloud

6:19

44

Gatsby Plugin Image

Use gatsby-plugin-image for automatic image resizing, formatting, and higher performance

8:11

45

useOnClickOutside Hook

Toggle a modal visibility with a useOnClickOutside hook

6:32

46

useWindowSize Hook

Create a hook to determine the width and height of the window

4:14

47

usePageBottom hook

Detect if the user scrolled to the bottom of the page

4:48

48

useLocalStorage Hook

Store an item in a browser's local storage

5:27

49

Three.js in React Part 1

Bring your website to life with beautiful 3D objects

17:33

50

Three.js in React Part 2

Bring your website to life with beautiful 3D objects

11:18