Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React path to public folder in css background image

Tags:

I am using Create-React-App and I want to add background image for my header section and I am doing this in that way:

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

After this I'm getting this error:

./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've set up homepage in package.json

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

In my older projects that works but today I cannot import this correctly.

like image 987
Freestyle09 Avatar asked Jul 19 '19 11:07

Freestyle09


People also ask

How do I reference a public folder in react?

To reference assets in the public folder, you need to use an environment variable called PUBLIC_URL . Only files inside the public folder will be accessible by %PUBLIC_URL% prefix.

How do I put a background image on a path?

Usage is simple — you insert the path to the image you want to include in your page inside the brackets of url() , for example: background-image: url('images/my-image. png');

How do you call a background image in react JS?

export default App; Output: Method 5: Add background image from src/ folder If the image resides inside the src directory, the user can import it inside the component filer and set it as the background image. In this file, we will import the image and set it as a background image of the div element.


2 Answers

They have changed that but I don't know why. Working path:

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

EDIT 2021

For people who think that it doesn't work:

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

like image 89
Freestyle09 Avatar answered Sep 19 '22 10:09

Freestyle09


you can import that image as

import Background from './Screenshot_11.png'

and use

background-image: `url(${Background})`
like image 42
Sabesan Avatar answered Sep 18 '22 10:09

Sabesan