Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use images in CSS files with ReactJS

Tags:

css

reactjs

I have an image inside src/assets/images folder in my ReactJs project. How can I use it in a CSS file as background-image without use relative paths?

I added in jsconfig.json the src folder in compilerOptions.baseUrl so in js files I can do:

import logo from 'assets/images/logo.svg'
<img src={logo} />

but what about css files? I have several folders and I'd like to avoid ugly strings like

background-image: url(../../../assets/images/logo.svg)

I'm using React 16.8.6

EDIT: I used create-react-app, so I haven't webpack files exposed and the ejection shoud be avoided.

like image 879
JustAnotherDeveloper Avatar asked Dec 10 '22 02:12

JustAnotherDeveloper


1 Answers

You can use (./) . Webpack automatically link the image for eg:-

.user-background{
    background: url("./images/all-bg-title.jpg") no-repeat center center;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -ms-background-size: cover;
    -o-background-size: cover;
     background-size: cover;
  }

Above image(all-bg-title.jpg) is at folder /src/images/all-bg-title.jpg

React Docs Link here

like image 122
It's EniGma Avatar answered Jan 02 '23 21:01

It's EniGma