Learn How to Use Images in Gatsby easily

Advertisements

Hello, Guys welcome back Here Learn How to Use Images in Gatsby easily this guide will show you how to utilise the gatsby-image plugin in conjunction with GraphQL queries to display optimised pictures within your Gatsby pages and React components.

The photos are lazy-loaded with a blurred SVG backdrop, the huge images are automatically scaled, and the meta data from the images is stripped. also Learn How to Download Speaker Notes in Google Slides

<Image src="sunset.png" alt="Sunset" />
Gatsby Images

The gatsby-image plugin generates numerous variants of an image for various display/device circumstances, which are served within the picture> element. Small images are inserted inline and served as base64, whereas SVG images are not handled.

Advertisements

Here’s how the image is served inside the HTML:

<div class="gatsby-image-wrapper" style="position: relative; overflow: hidden;">
  <picture
    ><source
      srcset="
        /static/images/6d161/175833.png 150w,
        /static/images/630fb/175833.png 300w,
        /static/images/2a4de/175833.png 600w,
        /static/images/40a00/175833.png 647w
      "
      sizes="(max-width: 600px) 100vw, 600px" />
    <img
      sizes="(max-width: 600px) 100vw, 600px"
      srcset="
        /static/images/6d161/175833.png 150w,
        /static/images/630fb/175833.png 300w,
        /static/images/2a4de/175833.png 600w,
        /static/images/40a00/175833.png 647w
      "
      src="/static/images/2a4de/175833.png"
      alt="Upload files from Google Drive"
      loading="lazy"
      style="position: absolute; top: 0px; left: 0px; width: 100%; height: 100%; object-fit: cover; object-position: center center; opacity: 1; transition: opacity 500ms ease 0s;"
  /></picture>
</div>

Step 1: Create the Images Folder

Create a subfolder called images in your Gatsby directory’s src folder. This folder should contain all images that will be served by the Gatsby images plugin.

Step 3: Install the Gatsby Image plugin

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

Step 3: Update the Gatsby Configuration

Update your gatsby-config.js file to include the image plugins as well as to read the image files in your images folder.

const path = require(`path`);

module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: path.join(__dirname, `src`, `images`),
      },
    },
    `gatsby-plugin-sharp`,
    `gatsby-transformer-sharp`,
  ],
};

Step 4: Create the Image Component

Create an Image.js file in the src/components folder. The maximum width of the generated image file is set to 600 pixels here, but you can change it to suit the layout of your Gatsby site. also Learn How to Use Google Sheets with D3.js and Google Visualization

Advertisements
import React, { useMemo } from "react";
import { graphql, useStaticQuery } from "gatsby";
import Img from "gatsby-image";
import PropTypes from "prop-types";

const Image = ({ src, ...rest }) => {
  const data = useStaticQuery(graphql`
    query {
      images: allFile(
        filter: { internal: { mediaType: { regex: "/image/" } } }
      ) {
        edges {
          node {
            relativePath
            extension
            publicURL
            childImageSharp {
              fluid(maxWidth: 600) {
                ...GatsbyImageSharpFluid
              }
            }
          }
        }
      }
    }
  `);

  const match = useMemo(
    () => data.images.edges.find(({ node }) => src === node.relativePath),
    [data, src]
  );

  if (!match) return null;

  const { node: { childImageSharp, publicURL, extension } = {} } = match;

  if (extension === "svg" || !childImageSharp) {
    return <img src={publicURL} {...rest} />;
  }

  return <Img fluid={childImageSharp.fluid} {...rest} />;
};

Image.propTypes = {
  src: PropTypes.string.isRequired,
  alt: PropTypes.string,
};

export default Image;
Gatsby Image GraphQL Query

The GraphQL query filters all files with image mimeTypes and then compares the image’s relativePath to the fileName supplied in the src props.

If the file is located, it examines the file’s extension. SVG pictures are served uncompressed, but all other image formats are compressed and optimised.

Step 5. Embed Images in Gatsby

Now, in the images/ folder, copy the image that you want to utilise in your React component / Gatsby page. Assume the file’s name is sunset.png. Use the new Image tag to include the image in your component.

import Image from "src/components/Image";

const Sunset = () => {
  return (
    <>
      <p>Sunset Image</p>
      <Image
        src="sunset.png"
        className="mx-auto shadow-xl"
        alt="Sunset Image"
        style={{
          border: "10px solid green",
        }}
      />
    </>
  );
};

export default Sunset;

Custom CSS styles, classes, alt tags, and all other properties accessible with the HTML img> tag can be used.

Advertisements

Leave a Comment