CSS background image referencing in React to the public folder's path

I am currently working on a project using Create-React-App and I am trying to set a background image for my header section. Here is how I'm attempting to do it:

background-image: url('~/Screenshot_11.png');

However, I encountered an error when trying to import the image:

./src/styles/main.scss (./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-5-1!./node_modules/postcss-loader/src??postcss!./node_modules/sass-loader/lib/loader.js??ref--6-oneOf-5-3!./src/styles/main.scss) Module not found: You attempted to import ../../../../../../../Screenshot_11.png which falls outside of the project src/ directory. Relative imports outside of src/ are not supported.

I have already specified the homepage in my package.json file as follows:

"homepage": "http://localhost:3000",

This method has worked for me in previous projects, but for some reason I am having difficulty importing the image correctly this time around.

Answer №1

They have recently made a change, but the reason is unclear to me. The current path being used is:

background-image: url('/Screenshot_11.png');

UPDATE 2021

For those who are experiencing issues with this method:

https://codesandbox.io/s/agitated-turing-gsnr3

Answer №2

you have the option to bring in the image like this:

import Pic from './Image.png'

then apply it using:

background-picture: `url(${Pic})`

Answer №3

I'm still having trouble getting this to work with images in the public directory.

UPDATED on March 20, 2021

When it comes to using in .css files, there seems to be a major issue (perhaps a bug?) in the create-react-app (react-scripts) package version 4.x.
Specifically, the problem lies within the 'css-loader' package version 4.x.
Using the 3.x branch seems to resolve this issue.

You can refer to the related problem on the GitHub repository:
https://github.com/facebook/create-react-app/issues/9870
(there are several other issues as well).

No solutions have been provided yet, but there are some mentioned workarounds available. The choice of workaround depends on your project's needs.

Here are some possible workarounds:

  • Downgrade to react-scripts 3.4.x

  • Avoid using URLs in CSS files :) You can still use them in .JSX (inline styles) or include them in .html. These file types are not processed by css-loader.

  • Reconfigure webpack to add url:false to css-loader options (by either ejecting CRA or using tools like: https://github.com/gsoft-inc/craco or https://github.com/timarney/react-app-rewired. (Sample configurations can be found on the GitHub issue page)

  • Utilize the new feature of css-loader https://github.com/webpack-contrib/css-loader/pull/1264 (released in version 5.1.0, with the current last version being 5.1.3; you can specify this version in package.json by adding: "resolutions": { "css-loader": "5.1.3" } (at root level))

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 some ways I can integrate my Json object into my IONIC app rather than relying on a hardcoded object?

I stumbled upon this IONIC app's services.js file and found an example using a hardcoded object called "employees." Instead of using the hardcoded object, I wanted to use a JSON file. However, my attempt to make this change did not work as expected. I ...

Issue encountered with pnpm dev: Unable to locate module for contentlayer/generated

I have encountered an issue while running the development server for my Next.js project using pnpm. The server starts successfully, but I am facing an error related to the contentlayer/generated module. Here is the error message I am receiving: ... - erro ...

Ensuring that the two columns in a responsive grid have equal heights is essential for maintaining a

I am currently working on a responsive website with a main content area (.content-wrapper) and a sidebar area (.search-listing). My goal is to make sure that both columns have the same height. I attempted to achieve this using the following jQuery code: j ...

Deciphering a JSON Array with GSON

Struggling with extracting a value from a basic JSON array after hours of unsuccessful attempts. Any guidance on the parsing process would be highly appreciated. Apologies for any confusion in my question wording. I have tried using JsonReader to read the ...

Incorporate a new CSS class into a DIV using JavaScript

Sample HTML: <div id="bar" class="style_one"></div> Is there a way to include the class style_two without deleting style_one? final outcome: <div id="bar" class="style_one style_two"></div> ...

Ways to center align text in a div vertically

I'm working with 2 divs that are floating side by side. The left div contains a part number, which is only one line. The right div holds the product description, which can span multiple lines. I am looking for a way to vertically align the text in t ...

the slider HTML control is missing a value

Exploring the Range Input Type in HTML When adjusting the value on a slider (Range input type), that value is displayed in a textbox. However, making the same adjustment in the textbox does not update the slider's value. Below is the code snippet: & ...

Using HTML5 Canvas: Implementing an Image.onload() function through Image.prototype

I am trying to create a simple function that will refresh the canvas automatically when an image is loaded. The idea is to be able to use code like this: var map = new Image(); map.onloadDraw(); map.src = "images/" + worldmapCanvasShapeImage; Currently, ...

React Hooks: In useEffect(), unable to modify parent component's state

Within my component, I have a form for users to input a title, description, and images. This component is nested within its parent component, and I want the form data to be saved if the user switches sections and returns later without losing their progress ...

When is the right time to develop a Node.js application using Typescript with dockerization

Currently, I am developing a full stack TypeScript application using Express for the server and React for the client. The folder structure of my project is organized as shown below: . ├──client/ <-- React app ├──server/ <-- Express serve ...

Having trouble opening the Swipeable Drawer on React using Material-UI with a swipe gesture?

Currently, I am working on a new project where I am attempting to incorporate a "menu" or drawer that opens when the user swipes from the left side of the screen. I have successfully implemented this functionality using a codeSandBox, which you can check o ...

Is it possible for me to save external CDN JavaScript files to my local system?

Normally, I would include scripts from other providers in my application like this: <script src="https://apis.google.com/js/api.js"></script> However, I am considering whether it is feasible to simply open the URL , and then copy and paste th ...

Swapping stylesheets using a hyperlink - a simple guide

Currently, I am creating a website that utilizes PHP, XHTML strict, and jQuery. The main goal is to ensure the site is adaptable for mobile and desktop devices by implementing the principles of Responsive Web Design. This involves serving different stylesh ...

Using two loops/arrays in JavaScript to generate a rating score

I want to create a simple rating component with the following appearance: ◼◼◼◻◻ (score: 3 out of 5) Here is my JSX code snippet: var score = 3; var range = 5; { [...Array(range)].map((e, i) => ( <div className="rating-item" ...

Testing Form with Select using Ant Design components and React Testing Library

I'm having trouble testing a customized Select input within an Ant Design Form that is pre-filled with initial values. The test is failing because the Select component is not receiving a value. What would be the best approach to properly test this "cu ...

Is Flash consistently positioned above the other elements? Can it be corrected using CSS

Hey there, I just uploaded a video from YouTube onto my website and noticed that the footer, which is fixed, is being overlapped by the video. Is there any way to resolve this issue? Perhaps some CSS tricks or hacks? Any assistance would be highly appreci ...

What is the process for submitting information to my Next.js API endpoint?

As part of my learning journey with Next.js, I am currently developing a test e-commerce website. To enhance the functionality, I am integrating a checkout system using Stripe. Initially, I was able to successfully implement the checkout feature with stati ...

Is it possible to simultaneously run both an npm server and a proxy in separate directories with just one command in

We are currently working on a project that involves a 'server' folder and a 'client' folder. In order to run the project, we have to navigate to the 'server' folder, enter 'npm run nodemon' in the terminal, and then ...

acquiring data via fetch (transferring information from javascript to php file)

I'm completely new to using fetch and not familiar with Ajax. Currently, I am attempting to transfer data from a JavaScript file (node.js server) to a PHP file (Apache server). The data being sent consists of 2 JSON values labeled as "a" and "b". T ...

The performance of the Next.js <Image /> component is sluggish on Netlify but significantly faster on Vercel

I have a fairly simple Next.js application and I am utilizing the <Image /> component in Next.js to display two small images like this: <Row className="justify-content-center m-0 mt-3 text-center"> <Col xs={4} md={3} lg={2} class ...