Learn Gatsby Β· 8/12

Mastering Images and Media Assets

7 min read

Mastering Images and Media Assets in Gatsby πŸ–ΌοΈ

Welcome, aspiring web developer! Today, we're diving into a crucial aspect of modern web development: handling images and media. While they make your site visually appealing, they can also be the biggest culprits for slow load times. But fear not! Gatsby has some powerful tools to make your images lightning-fast. πŸš€


1. The Performance Problem with Standard Web Images πŸ€”

Let's start by understanding the problem we're trying to solve. When you use a standard <img> tag in HTML, you're often serving a one-size-fits-all image. This can lead to some serious performance bottlenecks.

The Core Problem:

Imagine you have a beautiful, high-resolution photograph that's 4000 pixels wide. That's fantastic for a large desktop monitor, but what happens when someone visits your site on a tiny mobile screen? They still have to download that massive image file, even though their screen can't possibly display all those pixels. It's like trying to fit an elephant into a Mini Cooper – a huge waste of resources! πŸ˜πŸš—

This leads to:

  • Slow Load Times: Larger image files take longer to download, especially on slower network connections. This can lead to a frustrating user experience where visitors are staring at a blank space, waiting for your images to appear.
  • Wasted Bandwidth: For users on limited data plans, downloading unnecessarily large images can be costly.
  • Poor User Experience: If your site is slow and clunky, visitors are more likely to leave and not come back. In the fast-paced world of the internet, every second counts.

How do we traditionally solve this?

In the old days, you might have manually created multiple versions of each image – a small one, a medium one, and a large one – and then used complex CSS or JavaScript to serve the right one based on the user's screen size. This was a tedious and error-prone process. Who has time for that? 😫

This is where Gatsby's image processing capabilities come to the rescue, automating this entire process and making your life as a developer much, much easier.


2. Configuring gatsby-plugin-image and Sharp Image Processing βš™οΈ

To solve the performance problems we just discussed, we'll use two key players: gatsby-plugin-image and gatsby-plugin-sharp.

  • gatsby-plugin-image: This is the main plugin that provides the React components we'll use to display our optimized images.
  • gatsby-plugin-sharp: This is the powerhouse that sits behind the scenes. It uses the incredibly fast Sharp image processing library to resize, optimize, and transform your images.

Think of gatsby-plugin-sharp as a skilled photo editor who can instantly create multiple versions of your images in different sizes and formats, and gatsby-plugin-image as the smart frame that knows exactly which version to show to each user.

Installation and Setup:

Let's get our hands dirty and set this up. The process is straightforward.

  1. Install the necessary packages: Open your terminal and run the following command in your Gatsby project's root directory:

    bash
    npm install gatsby-plugin-image gatsby-plugin-sharp gatsby-transformer-sharp gatsby-source-filesystem
  2. Configure gatsby-config.js: Now, you need to tell Gatsby to use these plugins. Open the gatsby-config.js file at the root of your project and add the following to the plugins array.

    javascript
    module.exports = {
      plugins: [
        `gatsby-plugin-image`,
        `gatsby-plugin-sharp`,
        `gatsby-transformer-sharp`,
        {
          resolve: `gatsby-source-filesystem`,
          options: {
            name: `images`,
            path: `${__dirname}/src/images`,
          },
        },
      ],
    }
    • gatsby-plugin-image: Enables the core image optimization functionality.
    • gatsby-plugin-sharp: The low-level plugin that powers the image transformations.
    • gatsby-transformer-sharp: Creates ImageSharp nodes from your images, which you can then query with GraphQL.
    • gatsby-source-filesystem: This plugin allows you to source files from your local filesystem. In this configuration, we're telling it to look for images in the src/images directory. You can customize this path to wherever you store your images.

A Funny Exaggeration: Without these plugins, your Gatsby site is like a chef who insists on serving a whole, uncut watermelon to every single customer, regardless of whether they wanted a tiny slice or the whole thing. With the plugins, your chef is now a master fruit ninja, instantly slicing and dicing that watermelon into the perfect portion for each person. πŸ‰πŸ”ͺ


3. Rendering Fixed Assets with the StaticImage Component 🏞️

Now for the fun part! Let's actually display some optimized images. For images that are the same every time the component is used (like a logo, an icon, or a hero image on your homepage), we'll use the StaticImage component.

The Concept:

The StaticImage component is incredibly easy to use. You can think of it as a super-powered <img> tag. You provide the path to your image, and gatsby-plugin-image handles all the optimization for you at build time.

How to Use It:

Let's say you have a logo file at src/images/logo.png. Here's how you would display it in one of your components:

jsx
import React from 'react';
import { StaticImage } from 'gatsby-plugin-image';

const Header = () => (
  <header>
    <StaticImage
      src="../images/logo.png"
      alt="My Awesome Site Logo"
      placeholder="blurred"
      layout="fixed"
      width={200}
      height={100}
    />
  </header>
);

export default Header;

Breaking Down the Props:

  • src: The relative path to your image file from the component where you're using StaticImage.
  • alt: Essential for accessibility! Always provide a descriptive alt tag.
  • placeholder: This determines what the user sees while the image is loading. Common options are blurred (a blurry, low-resolution version of the image) and tracedSVG (a traced outline of the image).
  • layout: For StaticImage, you'll often use fixed. This means the image will have a fixed width and height. You can also use constrained (the image will scale down to fit its container, but not scale up larger than its original size) and fullWidth (the image will stretch to the full width of its container).
  • width and height: When using the fixed layout, you need to specify the dimensions of the image.

Interesting Fact: The "blur-up" effect you see with the blurred placeholder is not just a pretty animation. It's a clever performance optimization that gives the user an immediate visual cue that an image is loading, making the perceived load time much faster.


4. Rendering CMS/Dynamic Images with the GatsbyImage Component πŸ–ΌοΈ

What about images that aren't static? What if you're pulling in blog post cover images from a Content Management System (CMS) like Contentful, or if the image changes based on the props passed to a component? For these dynamic scenarios, we use the GatsbyImage component.

The Concept:

The key difference between StaticImage and GatsbyImage is how they get their image data. With StaticImage, you provide a direct path to the image file. With GatsbyImage, you'll use a GraphQL query to fetch the optimized image data.

The Workflow:

  1. Query the image data using GraphQL: In your page or component, you'll write a GraphQL query to get the image data.
  2. Pass the data to the GatsbyImage component: The result of the GraphQL query is then passed as a prop to the GatsbyImage component.

Example with a Local Image (can be extended to a CMS):

First, let's query for a specific image in our page's GraphQL query:

graphql
export const query = graphql`
  query {
    file(relativePath: { eq: "blog/avatars/john-doe.jpg" }) {
      childImageSharp {
        gatsbyImageData(layout: FIXED, width: 75, height: 75)
      }
    }
  }
`;

Here, we're using the file query to find a specific image and then using the gatsbyImageData resolver to get all the necessary data for our optimized image.

Now, in our component, we can use this data with the GatsbyImage component:

jsx
import React from 'react';
import { graphql } from 'gatsby';
import { GatsbyImage, getImage } from 'gatsby-plugin-image';

const BlogPost = ({ data }) => {
  const image = getImage(data.file);

  return (
    <article>
      <h1>My Awesome Blog Post</h1>
      <GatsbyImage image={image} alt="A portrait of John Doe" />
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit...
      </p>
    </article>
  );
};

export default BlogPost;

Key Points:

  • getImage: This is a handy helper function from gatsby-plugin-image that makes it easier to get the image data from your GraphQL query result.
  • image prop: The GatsbyImage component takes an image prop, which is the result of your GraphQL query.

Real-World Scenario:

Imagine you have a blog, and each blog post has a cover image that you manage in a CMS. When you build your Gatsby site, it will fetch the data for each blog post, including the URL of the cover image. gatsby-transformer-sharp will then download that image, create all the optimized versions, and make the data available through GraphQL. Your blog post template will then use a GraphQL query to get the optimized image data and pass it to the GatsbyImage component. This all happens automatically at build time, so your users get lightning-fast images without you having to manually optimize anything. How cool is that? 😎


Further Reading & References πŸ“š

Challenge

You are building a component for a blog post page in a Gatsby application. Your task is to correctly implement Gatsby's image components for both a static site logo and a dynamic feature image fetched via GraphQL.

  1. Import StaticImage, GatsbyImage, and getImage from the gatsby-plugin-image package.
  2. Directly below the <h1> element, render a static logo using the StaticImage component. The image is located at ../images/logo.png. It must have an alt text of "Site Logo", a layout of constrained, and a placeholder of blurred.
  3. The data for the dynamic feature image is passed into the component via the data prop. Create a variable named image and use the getImage helper function to process the image data located at data.markdownRemark.frontmatter.featureImage.
  4. Render the dynamic feature image using the GatsbyImage component. Pass the image variable you just created to the correct prop, and use the featureImageAlt from the component's data prop for the alt text.
  5. In the multi-line comment at the bottom of the file, list the four essential Gatsby plugins required to source local images and enable GraphQL transformations for gatsby-plugin-image.

Expected result

Your final code should be a React component that correctly imports StaticImage, GatsbyImage, and getImage from gatsby-plugin-image. It must feature a StaticImage component configured with the specified src, alt, layout, and placeholder props. The component should also correctly use the getImage helper to process the GraphQL data and pass the result to a GatsbyImage component, along with the dynamic alt text. Finally, the comment block should list gatsby-plugin-image, gatsby-plugin-sharp, gatsby-transformer-sharp, and gatsby-source-filesystem.

jsx

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.