Open In App

Gatsby Images

Last Updated : 31 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Gatsby is a free and open-source framework based on React that helps developers build blazing-fast websites and apps. Gatsby sites are fully functional React apps, so you can create dynamic web applications that are fast, responsive, and secure.

Using images is a challenge on any website. To use them for great performance across devices, you need multiple sizes and resolutions of each image. Luckily, Gatsby has several useful plugins to do so.

Create a new Gatsby Application

Step 1: Run the below code in the terminal to create a new gatsby site.

npm init gatsby

Give the name ‘gfg’ to the application project.

Step 2: Move to the new ‘gfg’ folder using the below command.

cd gfg

Project Structure:

 

Handling Images in Gatsby

It is very difficult to handle the responsiveness and quality of images in any framework, but in gatsby, we have a plugin that we can use to handle images very easily.  To use the plugin, follow the below steps.

Step 1: Install the plugin using the below command in the terminal:

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

Step 2: Add the plugins to your gatsby-config.js file:

Javascript




require("dotenv").config({
  path: `.env.${process.env.NODE_ENV}`,
})
module.exports = {
  siteMetadata: {
    siteUrl: `https://www.yourdomain.tld`,
  },
    
  plugins: [
    `gatsby-plugin-image`,
    `gatsby-plugin-sharp`,
    `gatsby-transformer-sharp`,
  ],
}


Step 3: Use the plugin to display images. For this, add the below code in your index.js file. We are loading a demo image with the name ‘logo.png’.

Javascript




import * as React from "react"
import { StaticImage } from "gatsby-plugin-image"
  
const IndexPage = () => {
  return (
    <main >
      <h3>GeeksforGeeks - Below is the image</h3>
      <StaticImage src="logo.png" alt="Demo Image" />
    </main>
  )
}
  
export default IndexPage;


Run the application: Use the below code in the terminal to start the application.

npm run develop

Output:

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads