0

I am learning Gatsby. I have a component called Hero which is for displaying a banner for the blog I am building.

import React from 'react';
import styled from '@emotion/styled';
import { Link, graphql, useStaticQuery } from 'gatsby';

const ImageBackground = styled('div')`
  background-image: url('images/plans-background.jpg'); <--- this url doesn't make sense to me
  background-position: top 20% center;
  background-size: cover;
  /* background-color: red; */
`;

const Hero = () => {
  return (
    <ImageBackground>
      <h1>Frontend Masster dsfsdfsd</h1>
      <p>
        hello
        <Link to="/about">learn about me</Link>
      </p>
    </ImageBackground>
  );
};

export default Hero;

I'm using the screenshot to show the folder structure enter image description here

according to the structure, in order to reach the background image I need a url like this

`../../../static/images/plans-background.jpg`

And that's what the IDE prompted me to type when trying to reach the image file. However this url doesn't work as expected. There's no background image showing. and I changed it to

`images/plans-background.jpg`

The background image showed up magically.

So I don't understand why this url is working. Is it something special about the folder static or is Gatsby doing something behind the scene?

Also when I opened up the devtool to inspect the resources that got loaded, I didn't find this static file, neither the background image file.

I am really trying to understand how these pieces work together enter image description here

Joji
  • 4,703
  • 7
  • 41
  • 86
  • Did you properly configure `gatsby-source-filesystem` on your `gatsby-config`? – wentjun May 30 '20 at 02:22
  • @wentjun Hi I was following a tutorial and in the tutorial the config for `gatsby-source-filesystem` is only very bare minimal. it looks like this ` { resolve: 'gatsby-source-filesystem', options: { name: 'posts', path: 'posts', }, },` – Joji May 30 '20 at 03:37
  • Does this answer your question? [Gatsby: Set background image with CSS](https://stackoverflow.com/questions/51776791/gatsby-set-background-image-with-css) – coreyward May 30 '20 at 15:45

1 Answers1

1

Yes, this is the expected behavior for your assets in /static, read more about it in the docs: Using the Static Folder.

However, adding your images there is not a best practice because they won't be optimized with Gatsby's build time image processing and gatsby-image.

The docs also have good resources for this: Using Gatsby Image to Prevent Image Bloat, or Working with images in Gatsby.

Robin Métral
  • 3,099
  • 3
  • 17
  • 32