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
}

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

Ensure that the navigation menu is consistently displayed properly, without any of its contents extending beyond the

I am experiencing an issue with the navigation menu on my website. Everything looks great in normal view, but when I resize the browser window to a smaller width, the menu ends up overflowing below the main content. I want the navigation menu to always dis ...

Tips on how to engage in a spontaneous audio experience

I am currently developing a Discord bot with the intention of having it play a random mp3 file upon joining a voice channel. case"join": message.delete( {timeout: 5000}) const voiceChannel = message.member.voice.channel ...

Overriding a shared module service in Angular from a separate module: A step-by-step guide

I am working with various modules such as SchoolModule, UniversityModule, and SharedModule The SharedModule includes a BaseService that both the SchoolModule and UniversityModule providers are utilizing as an extension When loading the SchoolModule, I ne ...

Experiencing issues with sending log messages symbolicatedStack on react native and expo

After updating to the latest versions of react (0.62.2) and expo (37.0.12), most things were working fine. However, I kept encountering an error screen that would pop up each time I reloaded the app or shortly after an error occurred. console.error: There ...

"Need help solving the issue of generating a random number for a Firebase DB column after adding a new user

Whenever I add a new user using JavaScript, it generates a random number below the Admins column like this. However, I want to adjust this so that it appears as shown in these tables, displaying the username value. If anyone can help me modify the code acc ...

Determine the necessary adjustment to center the div on the screen and resize it accordingly

Currently, I am in a situation where I must develop a piece of code that will smoothly enlarge a div from nothing to its final dimensions while simultaneously moving it down from the top of the screen. Each time this action is triggered, the final size of ...

Challenges with loading content on the initial page load using the HTML5

Upon page load, I wanted to save the initial page information so that I could access it when navigating back from subsequent pages. (Initial Page -> Page2 -> Initial Page) After some trial and error, I ended up storing a global variable named first ...

What is the most effective way to share data among components in React?

I recently delved into learning about react and find myself puzzled on how to pass data between two components. Presently, I have set up 2 functions in the following manner: First, there's topbar.tsx which displays information for the top bar, inclu ...

Getting an input value dynamically in a React variable when there is a change in the input field

I am having an issue with my search text box. I need to extract the value onchange and send a request to an API, but when I try using the normal event.target method, it shows an error. How can I fix this? The problem is that onchange, I need to call a func ...

Updating default values in reactive() functions in Vue 3: A step-by-step guide

Currently, I am in the process of developing an application using Nuxt 3 and implementing the Composition API for handling async data. The specific scenario I am facing is this: I have a page that displays articles fetched from the database using useLazyFe ...

A guide on incorporating translated routes (by translating the route paths) within a NextJS application

I am currently working on a NextJS web application that will be deployed in multiple countries, with each deployment requiring changes only to the env.country variables. However, I am facing an issue with routes that have significant slugs needing translat ...

`Must have content in file input in order to be saved to MongoDB`

When attempting to save a registry in MongoDB using Node.js, it seems that the operation fails if an image is not selected. I would like the inclusion of an image in this process to be optional, rather than mandatory. router.post("/", upload.single("image" ...

How can I modify the TextField's borderBottom style to be 'none' when it is disabled?

While working within a data cell, I encountered an issue with stacking text. To workaround this obstacle, I opted to create a text field, assign it a value and helper text, disable the field, and change the text color to black when disabled. My current cha ...

Retrieving JavaScript array data following a page reload

I am facing an issue with updating an array dynamically in my C# server-side code and then utilizing the updated data in a JQuery function on my webpage. When the page first loads, the array is filled with some default values by C#. However, when a user ma ...

Locating the Active Object's Coordinates in fabric.js

When using fabric js, I have successfully drawn various shapes like circles and rectangles. However, I encountered an issue while trying to obtain the coordinates of the rectangle using the fabric.rect() method. canvas.getActiveObject().get('points& ...

Incorporate images into ReactJS Components without the need to save them locally as files

<img src={BASENAME+"/src/images/cabecera_CE.jpg"} id="idImgCabecera" alt="Universidad Politécnica de Cartagena" class="img-responsive"/> and I am looking to do the following: import PHOTO from './../images/cabecera_CE.jpg' <img src= ...

The input element captures the exact x and y coordinates of where the mouse was clicked

I have a requirement to submit a page, and I have opted to utilize the <input> element for this purpose with an image that zooms slightly when hovered over. Due to the unusual nature of my query, I was unable to find any relevant information about t ...

Learn how to retrieve data from the console and display it in HTML using Angular 4

Need help fetching data inside Angular4 HTML from ts variable. Currently only able to retrieve 2 data points outside the loop. Can anyone assist with pulling data inside Angular4? HTML: <tr *ngFor="let accept of accepts"> ...

Resolving TypeError: matchesSelector method is not recognized within React component

I am currently integrating masonry-layout from the official website to create a masonry grid within my component. However, I encountered an issue where clicking on a rendered element triggers the error message TypeError: matchesSelector is not a function. ...

Aligning text in the middle of two divs within a header

Screenshot Is there a way to keep the h4 text centered between two divs? I want it to stay static regardless of screen resolution. Currently, the icon and form remain in place but the h4 text moves. How can I ensure that it stays in one spot? <!doctyp ...