Having trouble importing from the public folder in CSS with Create React App?

While working on a project initialized with Create React App, in the public folder there is an assets directory containing a file named logo512.jpg.

When I use this file in a component like so:

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

Everything functions correctly. But when I try to reference the same file in a CSS file for the identical component like this:

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

I encounter the error message

Can't resolve '/assets/logo512.jpg' in DIRECTORY_OF_COMPONENT/assets/logo512.jpg

Please note that DIRECTORY_OF_COMPONENT refers to the folder where the CSS file is located, not the public folder. How can I adjust the URL to point to the public folder instead?

Below you'll find the complete code snippet 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
}

https://i.sstatic.net/YDF7S.png

Answer №1

UPDATE:

CASE 1:

If your image is located in the public folder, the code should work as expected if you are using the assets folder directly within the public directory.

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

CASE 2:

If you need to use images from a location other than the public folder, you must import the image into your React project first. Ensure that the Path is correct and references your image properly.

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

Then, you can use it in the src attribute.

<img src={MyImage}/>

Case 3: When applying an image to a block-level element using CSS:

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

This approach should work correctly, assuming your relative path is accurate in relation to the CSS file.

NOTE: For SVG images, React now provides a component-based method where we import our SVG using ReactComponent.

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

return(<Logo/>)

Answer №2

I encountered a similar issue and found the initial response too ambiguous.

Just to clarify: When you reference `assets` in your CSS, it points to the `src/assets` directory within your project structure.

Here's an example of me incorporating a static asset in my CSS:

@font-face {
  font-family: "ITC Clearface";
  src: url("assets/ClearfaceStd-Regular.woff2") format("woff2");
  font-weight: 400;
  font-style: normal;
}

If you're having trouble with the path, pay attention to any error messages from the compiler, for instance:

Module not found: Error: Can't resolve 'assets/somefile' in '/home/mike/Code/myapp/website/src'

Check if the file actually exists by running this command (in bash or powershell):

ls /home/mike/Code/myapp/website/src/assets/somefile

If the file isn't found, there might be a typo in the filename! In my scenario, I discovered a minor spelling mistake in the font file name used in my CSS.

Answer №3

When it comes to adding an image, I have found two effective methods:

  1. One approach is to import the image from the public folder and use it in a tsx component like this:
const myBackground = './images/background.png';
// Then, you can simply use this variable wherever needed, such as:
<div style={{backgroundImage: `url('${myBackground}')`}}</div>
// Make sure to also specify width and height for the div to display the image correctly
  1. Alternatively, you can directly import the image into your CSS by hard-coding the full path, like so:
.my_background{
    background-image: url('../../../public/images/background.png') /* This specifies the full path to the public directory from your CSS/Sass file */
    // Add any additional CSS styles here
}

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 techniques can be used to create logos that adapt and transform seamlessly as the screen size varies?

The way Responsive Logos adjust their image width when you resize the browser is truly impressive. It seems like they are using SVG images, but I'm not entirely sure how they are able to make the image change dynamically. Could it be through the CSS c ...

Creating a custom React hook that takes a state variable as a parameter

There's a react function component that assigns an array of ids based on a user event when a link is clicked (triggering a popup with selectable options and a callback returning the selected element's id upon closure). These ids are then passed t ...

Stop the bubbling effect of :hover

How can the hover effect be prevented for the parent element when hovering over its children? Please take a look at the following code snippet: const parent = document.getElementById('parent') parent.onmouseover = function testAlert(e) { /* ...

Developing a custom React component library using Webpack and Typescript, however encountering issues with Webpack consistently bundling React

I'm currently in the process of developing an external component library using Webpack and TypeScript. Although it compiles without any issues, I encounter an error when attempting to use the library: Invalid hook call. Hooks can only be called ins ...

Issue encountered with asynchronous execution while utilizing AWS Cognito registration process

I am developing a user management system using Amazon Web Services called Cognito. Everything works fine locally, but I encounter issues when running it on a Wamp server. I cannot seem to pinpoint the cause... could it be due to asynchronous execution? ...

Displaying divs inline with overlapping child divs

As a beginner in CSS, I tackle the challenges of learning it every day. Despite feeling clumsy and not naturally adept at it, my determination is strong (although sometimes my brain feels like an old computer on the verge of overheating). My current goal i ...

Tips for adjusting the size of iframe content to fit its div area in Bootstrap 4 when the window is minimized

I recently started building a website and encountered an issue with resizing the window to fit an iframe containing a video within a div. I'm unsure where exactly in the CSS code I need to make adjustments for this. Can someone help me out? The websi ...

An anomaly where a mysterious symbol appears in front of every dollar sign in an HTML document

I have a code written in AngularJS to display the amount in dollars. However, there is an unwanted " Â " character appearing before every " $ " character in the HTML. I am looking for a way to remove this character. Your help is greatly appreciated. Thank ...

Evaluate redux-actions

Is there a way to effectively test React-redux actions using Jest? import { combineReducers } from 'redux'; import { handleActions } from 'redux-actions'; import * as actions from '../actions/index'; const background = handle ...

Ensure chip component (div) dynamically resizes its width to accommodate varying lengths of child text elements

I have a main container with two child elements (a text span and an image svg) created using the Material UI component library. My objective is to dynamically adjust the width of the chip based on the length of the text content inside it, while ensuring a ...

The boundary of embedded components

I am looking for CSS code that will allow me to arrange all elements with specific indents, such as placing the first element on the left side of the page, followed by an image with some indentation, and so on. <div class="container-fluid"> &l ...

Leverage TypeScript to access custom component properties and URL parameters from react-router-dom

In my react-router-dom setup, I have a route structured like this: <Route path="/result/:result" component={ResultsView} audio={audio} speechRecognition={speechRecognition} /> Furthermore, I have a component with specified props as follows ...

Can you explain the functionality of the return false statement within the validate plugin's submitHandler

While exploring the validator plugin examples, I stumbled upon a code snippet online: $('#testimonials-form').validate({ rules: { "t-title": { required: true, minlength: 5 }, "t-text": { ...

"Utilizing the power of React Redux toolkit to toggle the visibility of a

Just starting out with redux toolkit and I have a question about updating my modal within the reducer. I attempted to update state.modal to be action.payload but it doesn't appear to be working as expected. export const uiSlice = createSlice({ name: ...

Transferring binary fragments to Node.js for assembly into a complete file. Creating a file

Hey there, I'm in a bit of a bind. I'm trying to send file chunks using multiple XMLHttpRequest requests and then receive these parts in Node.js to reconstruct the original file from the binary data. The issue I'm facing is that the final f ...

Guide to implementing CSS3 transitions with prefixes using JavaScript

Is there a way to apply CSS styles using JavaScript when I don't have access to the CSS file? #fade div { -webkit-transition: opacity 1s; -moz-transition: opacity 1s; -o-transition: opacity 1s; -ms-transition: opacity 1s; transition: ...

Sending an AJAX request to a PHP file to retrieve data in JSON format

Greetings everyone, I am currently exploring the world of AJAX for sending information to a JSON file and I'm unsure about the structure of the .php file needed to process it. My experience with .php is quite limited. Can anyone guide me in the right ...

I'm having trouble getting my HTML to scroll properly

Apologies for asking a common question, but I'm facing a specific issue with scrolling that I can't seem to figure out. Below is the code snippet: * { font-family: Arial, Helvetica, sans-serif; text-align: center; font-size: 40px; } < ...

Unable to send image file and string via XHR is causing issues

This task may seem straightforward, but I've been struggling with it for hours. My goal is to upload an image file along with stringified coordinates to crop the image on the server-side. Below is my client-side code: var formdata = new FormD ...

Scrolling through menus horizontally

I am faced with a challenge where I have Menu items from Menu1 to Menu10, but the limited space on the web page prevents me from displaying all the menu items at once. Currently, I can only show 4 menu items - Menu4 to Menu7. To access the remaining menu i ...