Mr. A
Mr. A

Reputation: 333

Importing Public Folder Images In Src Css Files In Reactjs

I need to import some assets from public folder. I can do it easily in html; it wont give an error. However, I can not do it with css url() method. I need to do this since react encodes images that are smaller than 10Kb to base 64 and uses that encoded text instead of image path. As I've read in some articles, this does not benefit performance since css is a render blocking resource and adding to its text, makes parsing it longer.

Here's my folder structure:

folder structure

My .scss file is inside src/components and this is how i've tried importing the image:

background-image: url("/media_assets/img/footer-xsm.png");

And my package.json:

{
  "name": "roomeet",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@glidejs/glide": "^3.4.1",
    "@loadable/component": "^5.14.1",
    "@testing-library/jest-dom": "^5.11.5",
    "@testing-library/react": "^11.1.2",
    "@testing-library/user-event": "^12.2.2",
    "bootstrap": "^4.5.3",
    "js-cookie": "^2.2.1",
    "node-sass": "^4.14.1",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-lazyload": "^3.1.1",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.0",
    "source-map-explorer": "^2.5.2",
    "web-vitals": "^0.2.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "analyze": "source-map-explorer 'build/static/js/*.js'",
    "bundle-report": "webpack-bundle-analyzer --port 4200 dist/stats.json"
  },
}

Edit: This is the error that it's giving:

Error: Can't resolve '../media_assets/img/footer-xsm.png' in 'C:\VSCode Projects\rmt_cln\src\components' 

Upvotes: 3

Views: 1169

Answers (1)

jadinerky
jadinerky

Reputation: 100

i'm currently unable to comment so i'll have to write it as an answer, can you pleas try

background-image: url("./media_assets/img/footer-xsm.png");

if it didn't work just flag it as unuseful and go check this you'll find a solution there

Upvotes: 2

Related Questions