Gatsby utilized the background-image CSS style within the Emotion library for CSS-in-JS implementation

The background image is not visible with the current setup. To troubleshoot, I attempted to set the background to pink within const background and it worked. This confirms that Emotion is functioning correctly.

Upon inspecting with the React Dev Tools extension, I can see background-image: url(../images/page_backgroundgradient.png), url(../images/page_background.png); applied without any errors.

What could be causing my issue?

My folder structure is as follows:

frontend/
  src/
    images/
      page_background.png
      page_backgroundgradient.png
    pages/
      index.js

This is the index.js file where I am trying to add a background image:

...
import { css, Global } from "@emotion/core"

const background = css`
  background-image: url(../images/page_backgroundgradient.png), url(../images/page_background.png);
`
<div css={background}>
   ...
</div>

Answer №1

After reviewing the link you shared in your comment, it's evident that there are several ways to incorporate images/assets with gatsby:

  1. Retrieve the image using graphql
  2. import the image and get its path
  3. Place the image in the static directory

Getting Started

Assuming you have a component structured like this:

// src/pages/sample.js

import React from 'react'
import { css } from '@emotion/core'

export default () => <div css={css`
  width: 10rem;
  height: 10rem;
  background: url( ... );
`} />

Query Method

PublicURL

If you're utilizing any of the default starters, chances are your src/images folder is configured with gatsby-source-file-system, allowing Gatsby to recognize your images. Assuming you know the file name, you can query it as shown below:

{
//       ⇣ `base` refers to the file name along with its extension.
  file (base: { eq: "image.png" }) {
    publicURL
  }
}

By querying for the field publicURL, you'll receive the file's path:

export default ({ data }) => <div css={css`
  width: 10rem;
  height: 10rem;
  background: url(${data.file ? data.file.publicURL : 'your/fallback.png'});
`} />

export const query = graphql`
  query {
    file(base: { eq: "image.png" }) {
      publicURL
    }
  }
`

ImageSharp

Gatsby typically includes sharp, enabling image transformations and more. For instance, you can resize an image to 200px width through the following query:

export const query = graphql`
  query {
    file(base: { eq: "image.png" }) {
      childImageSharp {
        fixed(width: 200) {
          src
        }
      }
    }
  }
`

The result can be accessed at

data.file.childImageSharp.fixed.src
.

Importing Images

Leverage webpack for this purpose:

import myImagePath from '../relative/path/to/image.png';

export default () => <div css={css`
  width: 10rem;
  height: 10rem;
  background: url(${myImagePath});
`} />

Moving Images to static Directory

Create a folder named static in your root directory if it doesn't already exist. Proceed to transfer your image into it:

root
  |--src
  `--static
       `--image.png

All files within static will be directly copied during build, thus allowing you to reference the image like so:

export default () => <div css={css`
  width: 10rem;
  height: 10rem;
  background: url(/image.png);
`} />

If you're utilizing pathPrefix in gatsby-config.js, import withPrefix from gatsby and wrap it around the image path.


For a visual demonstration of the first two methods, check out this codesandbox.

We hope this information proves helpful!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are the steps for setting up a live commenting feature in a django-react application using channel, celery, and redis technologies?

Currently, I am developing a web application with Django serving as the backend and React handling the frontend. Within this application, there are multiple users associated with an organization or company. My goal now is to integrate a real-time commentin ...

Extend an array by Parsing JSON

I'm struggling to retrieve the JSON string from localStorage and add a new dish to it. It's not functioning correctly, can anyone lend me a hand? I am utilizing TypeScript. interface Dish { id: number; name: string; desc: string; ...

In Chrome, the $http GET request fails to send the JSESSIONID, but it functions properly on Firefox with AngularJS

Here is the code snippet I am working with: $http({ 'method': 'GET', 'url': 'http://www.example.com', 'withCredentials': true, headers: { 'Content-type': &apo ...

What is the best way to iterate through files within a directory and its nested subdirectories using electron?

I am currently working on developing a desktop application that involves scanning through a directory, including all subdirectories, to locate files containing specific characters in their filenames. Is it feasible to accomplish this task using Electron? ...

Invoking an *.aspx method from an external HTML file

Greetings, I am a newcomer to the world of web application development. I have successfully created an *aspx page that communicates with a webservice through a method returning a string. My next goal is to invoke this aspx method from a remote HTML 5 page ...

After setting up node.js, I encountered issues running "npm start" to begin my work on react js

I am attempting to set up React JS for the first time, but encountered an error after setting up node, npm, and the react app. When I run the "npm start" command, I receive the following errors: https://www.tutorialspoint.com/reactjs/reactjs_environment_s ...

Is it still relevant to use ng-repeat track by in AngularJS 1.6?

Is using track by in Angular 1.6 with ng-repeat still considered beneficial? Does it contribute to better performance? ...

JavaScript appendChild method not functioning properly with dynamically created image elements in JavaScript code

I recently encountered an issue while working on a website project. I was trying to create an img element using JavaScript, but ran into a problem when I tried to add the src attribute and then use the appendChild function. I'm unsure if I am missing ...

The FBXLoader encountered an issue locating the version number within the fbx file

I am encountering an issue while attempting to load a .fbx file. The loader.load function is throwing the following error message: "THREE.FBXLoader: Cannot find the version number for the file provided." Unfortunately, I am unsure of how to resolve this p ...

What is the proper way to send an AJAX request with the data type set to

I am currently working on creating my own POST request. Below is the function I have written: function sendPost(o) { var h = new XMLHttpRequest(); h.onreadystatechange = requestComplete; function requestComplete() { if (h.readyState = ...

Trigger a re-render in React using setState(null) and forceUpdate()

When using react 16, setState(null) no longer triggers an update according to the official documentation: The new behavior for calling setState with null is that it does not trigger an update. This gives you the control in the updater function to decide ...

Determine the specific value of an HTML table cell by specifying the column name for a specific row

One challenge I am facing is dynamically creating a table using JSON without knowing in advance the number of columns and/or rows that will be generated. I have successfully added a clicked event for the row that gets selected. In every table, there will ...

Updating the variable in Angular 6 does not cause the view to refresh

I am facing an issue with my array variable that contains objects. Here is an example of how it looks: [{name: 'Name 1', price: '10$'}, {name: 'Name 2', price: '20$'}, ...] In my view, I have a list of products bei ...

Adjust the CSS styling to ensure that the div or iframe expands to fit the entire height of the

Having trouble making a map embedded via an iframe on a WordPress page display responsively at full height independent of the device? Check out: . To clarify, by full height, I mean that the bottom of the map should not extend beyond the screen, eliminati ...

The properties '{ label: string; value: string; }' are required in type 'readonly never[]' for react-select, but they are missing

state = { groupPermissionValue: {label: '', value: ''}, } <Select instanceId="user-group" onChange={this.selectUserGroupOption} value={this.state.groupPermissionValue} options={this.state.groupPermission} i ...

Utilizing PHP and JavaScript in a multi-page setting

Apologies for the length of this post in advance. I've been struggling with a coding issue for quite some time now and haven't been able to find a solution. To provide more context and help to those who might assist me, I'm including most of ...

Is there a way to stop Bootstrap from automatically bolding the font?

When testing this simple example without the bootstrap link, everything seems to be working correctly: Hovering over any word changes its color to red, and when hovering away it returns to black. But as soon as the bootstrap link is included, the text bec ...

"Utilizing the power of React Redux toolkit to toggle the visibility of a

Just starting out with redux toolkit and I have a question about updating my modal within the reducer. I attempted to update state.modal to be action.payload but it doesn't appear to be working as expected. export const uiSlice = createSlice({ name: ...

Issue with res.redirect not functioning as expected

I am having some difficulty with the use of res.redirect() in my express application. After searching through other questions, I haven't found a solution that directly addresses my specific issue or is detailed enough to be useful. app.get(/\d& ...

looping through the multi-dimensional array using v-for

Interested in using v-for and I have encountered a scenario with an object structure as seen here: https://i.sstatic.net/wNguk.png Upon inspecting the dev console, the object looks similar to this: https://i.sstatic.net/jyqth.png My query is about how to ...