Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot import from public folder in CSS Create React App

In a project bootstrapped with Create React App, in my public folder I have a assets folder with the file logo512.jpg.

When I reference the file in a component like so

<div>
    <img src='/assets/logo512.jpg'/>
</div>

I everything works perfectly. However, when I reference the same file in a CSS file for the same component like so:

background {
    background-image: url('assets/logo512.jpg');
}

Then the error Can't resolve '/assets/logo512.jpg' in DIRECTORY_OF_COMPONENT/assets/logo512.jpg

Note that DIRECTORY_OF_COMPONENT is not the public folder but the folder the CSS file is in. How do I make it so the url references the public folder instead?

Below is the full code along with my file structure:

// HomePage.js

import React from 'react';
import 'tachyons';
import './HomePage.css';

function HomePage() {
    return (
        <div className="background tc">
            <div>
                <img src='/assets/logo512.jpg'/> //this works 
            </div>
        </div>
    );
}

export default HomePage;



// HomePage.css
.background {
    height: 100%;
    display: flex;
    align-content: center;
    justify-content: center;
    background: url('/assets/logo512.jpg'); //this does not work
}

File Structure

like image 364
Cirrus86 Avatar asked Sep 16 '25 14:09

Cirrus86


1 Answers

UPDATE:

CASE 1:

If you image is in the public folder. Then the code should work provided you are using assets folder right within the public folder.

Codesandbox Demo for all the three cases : https://codesandbox.io/s/images-not-loaded-hkzq1

CASE 2:

In case you want to use images from other than the public folder, You will need to import the image in your React project first. (Make sure the Path is correct and your image).

import MyImage from "./assets/logo512.jpg"

And then use in the src attribute.

<img src={MyImage}/>

Case 3: When using CSS to set image on a block level element:

.background  {
  height:200px; /* Make sure height of the div is given for image to be within*/
  background-image: url("assets/logo512.jpg");
}

This should work properly (provided you relative path is correct with regard to the CSS file)

NOTE: With SVG images React has come up with a component based way where we use as a component by importing our SVG with ReactComponent.

import { ReactComponent as Logo } from './logo.svg';

return(<Logo/>)
like image 135
Imran Rafiq Rather Avatar answered Sep 18 '25 10:09

Imran Rafiq Rather