reactjsgatsbygatsby-image

gatsby-plugin-image | <StaticImage /> Does not display the image


I want to optimize all the images on my Gatsby site and to achieve that I have installed the gatsby-image-plugin.

For the dynamic images, I am using the GatsbyImage Component and everything is working fine, no issues here.

The problem is when I want to render static images using the StaticImage Component.

Here is an example:

import laptop from '@images/laptop.png';

If I import the image and I use it this way:

<img src={laptop} alt='laptop' />

The image shows up correctly on the browser, but if I try to do this:

import { StaticImage } from 'gatsby-plugin-image';
<StaticImage src={laptop} alt='laptop' />;

The image is not showing up on the browser and I get the following message in the console:

Image not loaded /static/laptop-5f8db7cd28b221fc1a42d3ecd6baa636.png

And this error in the terminal:

Could not find values for the following props at build time: src Image not loaded /static/laptop-5f8db7cd28b221fc1a42d3ecd6baa636.png

I have tried to pass as src a link of a random image from the internet and the image was displayed on the browser! Why is it not working when I use the image that I have in my assets folder?

PS; Reading the plugin documentation I saw that there are some restrictions like you cannot pass images that are coming from the props, but this is not the case! I am importing the image directly from the assets folder.

Any leads, please? Thank you in advance.


Solution

  • PS; Reading the plugin documentation I saw that there are some restrictions like you cannot pass images that are coming from the props, but this is not the case! I am importing the image directly from the assets folder.

    You're importing the image from your assets folder, but you're still passing it to StaticImage as a prop. The correct usage is as follows:

    <StaticImage src='@images/laptop.png' alt='laptop' />
    

    Per the Gatsby Image Plugin documentation, src must be type string. You're currently passing an object {laptop}. Change it to a string with the images file path and it will display.