Guide to configuring a background image from the public folder in a React application using Create React App

How do I properly set a background image in a .css file located in the src folder?

src/Components/Component/Comp.css

.services {
  background-image   : url("./images/img-2.jpg");
  background-position: center;
  background-size    : cover;
  background-repeat  : no-repeat;
  color              : #fff;
  font-size          : 100px;
}

After encountering an error:

Error: ENOENT: no such file or directory, open 'C:\xampp\htdocs\react\react-website\src\images\img-1.jpg'

To fix it, I transferred the images folder from public to src, which resolved the issue. However, now I am facing difficulty accessing those images in a React Component, such as:

src/Components/Cards/Cards.js

<CardItem
src="./images/img-9.jpg"
text="Explore the hidden waterfall deep inside the Amazon jungle"
label="Adventure"
path="/services"
/>

src/Components/Cards/CardItem.js

const { src, text, label, path } = props

    return (
        <>
            <li className="cards__item">
                <Link className="cards__item__link" to={path}>
                    <figure className="cards__item__pic-wrap" data-category={label}>
                        <img src={ src } alt="Travel" className="cards__item__img" />
                    </figure>
                    <div className="cards__item__info">
                        <h5 className="cards__item__text">{text}</h5>
                    </div>
                </Link>
            </li>
        </>
    )

Even though no error is being displayed, the image simply does not appear.

How can I correctly store the images folder and access resources from .css and .js files?

Answer №1

If you prefer not to directly import an image into your component, you can still display the image using the following method:

var imageName = require('./images/img-9.jpg')
<img src={imageName} />

In this case, the `require` function is utilized for static "imports", requiring you to adjust your import statements.

Alternatively, you can achieve the same result with the following approach:

import imageName from './images/img-9.jpg';
<img src={imageName} />

This presents another way to accomplish the task.

Answer №2

Since your file is located at

src/Components/Component/Comp.css
and the image is in the public folder, you will need to navigate 3 levels up from the Comp.css file to access the image. You can achieve this by using a path like the following, which should work and may be suggested by your IDE:

<CardItem
src="../../../public/images/img-9.jpg"
/>

However, it is recommended to avoid placing images directly in the public folder. It is better practice to create an assets folder within your src directory, and then a images folder within the assets to store your images.

In this scenario, the path would be:

../../assets/images/img-9.jpg

Answer №3

Here is my unique approach:

const { source, content, tag, route } = props

    // In order to create a dynamic solution for reusing the component, I assigned the source value and complete route to a constant variable.
    // NOTE: Since it is an object, we need to access the default property
    const imageSource = require(`../../assets/images/${source}`).default

    return (
        <>
            <li className="cards__item">
                <Link className="cards__item__link" to={route}>
                    <figure className="cards__item__pic-wrap" data-category={tag}>
                        <img src={imageSource} alt="Travel" className="cards__item__img" />
                    </figure>
                    <div className="cards__item__info">
                        <h5 className="cards__item__text">{content}</h5>
                    </div>
                </Link>
            </li>
        </>
    )

Answer №4

As we approach the end of 2021, the ongoing discussion around a perplexing issue in the related repository continues to confound many users, especially those utilizing the most recent version of CRA (Create React App).

A single commit appears to be the culprit behind the chaos, leading to an intriguing tale that introduces you to a "famous guy" within the discussion. Dive into the details here.

For those grappling with the same problem and finding other solutions ineffective, the best course of action seems to involve relocating all images to the src folder. While not ideal and suitable only in specific scenarios, this approach currently stands out as the most viable option.

Personally, I opted to create a designated folder within src titled src/assets/images and transferred all my images there. To utilize any image from this folder in JSX files, the initial step is importing it, following a similar path as demonstrated below:

import deleteModalIcon from '../../../assets/images/delete_modal_icon.svg'

Subsequently, the imported image can be utilized as showcased:

<img src={deleteModalIcon} alt='' />

In my CSS file, situated at the top level of the src folder, I implemented the following method to incorporate an image:

.name:after {content: url('assets/images/edit_icon.svg');}

It's important to highlight the concerns raised within the discussion regarding disappearing images post-build.

To future readers: If a reliable solution or an official fix emerges for this issue during your time, kindly share it in the comments section =)

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

Jenkins Docker build fails for React app, while the local build is successful

When I run npm run build on my local machine, everything works perfectly. However, when I try to run it on a Docker image launched through Jenkins, I encounter some issues: Cannot find module: 'file-saver'. Make sure this package is installed. Y ...

I have created an Express.js application. Whenever I visit a page, I consistently need to refresh in order for the variables to appear correctly

Hello, I'm seeking some assistance. Despite my efforts in searching for a solution, I have not been successful in finding one. I've developed an application using Express.js that includes a basic form in jade. The intention is to display "Yes" i ...

Trouble arises when emitting events in Vue using eventHub

In the development of my component, there arises a need to emit an event at a specific point in its lifecycle. This emitted event is intended to be listened to by another sibling component. To facilitate this communication, I am utilizing an event hub. H ...

Incorporate a progress bar into the Material-UI table design

I have the following example of a Material-UI table: import React from "react"; import clsx from "clsx"; import { createStyles, lighten, makeStyles, Theme } from "@material-ui/core/styles"; import Table from "@mat ...

JavaScript form validation: returning focus to textfields

I am currently working on a project where I am using JQuery and JavaScript to create an input form for time values. However, I am facing challenges in getting the JavaScript code to react correctly when incorrect input formats are detected. I have a group ...

Experiencing issues while trying to publish on Cloudflare Workers?

To organize my project, I decided to create a folder named workers. Inside this folder, I followed these steps: Firstly, I initiated the project using npm init. Next, I installed @cloudflare/wrangler by running npm i @cloudflare/wrangler. This action resul ...

Navigating through route parameters and application logic

There is an endpoint / which may receive different get parameters for oAuth and logging in to an app. A function called queryAction has been created to handle these requests. Platforms like express can route at the path level but not the res.query level, ...

Can the ID attribute be used in the closing tag of an HTML element

Could this code be improved by properly closing the div with an ID: <html> <body> <div id="main"> </div id=main"> </body> </html> ...

What is the best way to determine if a radio button has been chosen, and proceed to the next radio button to display varied information?

The goal is to display the <div class="resp"> below each radio button when it is selected, with different content in each <div class="resp">. The previously selected <div class="resp"> should be hidden when a new radio button is chosen. O ...

Redirecting to a specified URL after submitting a POST request in Angular

I recently started learning Angular and decided to follow this tutorial on creating a MailChimp submission form. I made sure to customize the list information & id according to my own needs. However, after submitting the form, I encountered an issue wh ...

Implement tippyjs-react within individual cells of a table

I am facing an issue with implementing tooltips in table cells using tippyjs-react. The tooltips are not showing up as expected. I have tried adding tooltips to the Cell option in React Table by referring to the documentation: Cell: ({ value }) => { ...

The issue arises when trying to use both CSS Sprite and Background Gradient simultaneously in Chrome/Safari

Lately, I've been having issues with the gradient not displaying correctly in Webkit, although it seems to be working fine in Firefox. Could someone take a look and see if there's an error in how I set it up? Please disregard the images, as it&ap ...

Require assistance to resolve variable scope problems

Having trouble accessing the names array within the driver.executeScript method. Any suggestions on how to resolve this issue? var webdriver = require('selenium-webdriver'), By = webdriver.By, until = webdriver.until; var driver = new webdri ...

Tips for executing Cross-Origin-Requests from Firebase Hosting to an AWS Lambda function

Excuse me, I'm still new to web development. I have a basic single-page website hosted on Firebase hosting that retrieves some information from an AWS Lambda function (I didn't use Google Cloud because it didn't support outbound requests fo ...

Dynamic Namespaces in Socket.io is a feature that allows for

I am currently working on implementing multiple namespaces in my app. As I receive route parameters, I dynamically create new namespaces. For example: var nsp = io.of('/'); var className; app.post('/class/:classID',function(req,res){ ...

The Bootstrap 4 modal appears to be failing to load properly, as it is only

Trying to trigger a Bootstrap modal with a button click. Currently, there is one functioning modal on the page that works fine. However, when attempting to load another modal on a button click, only a faded screen appears. <button class="btn btn-green ...

"Is there a way to position a button at the bottom using HTML and

Is there a way to position my button after the reviews stars? The browser output screenshot shows the desired layout: https://i.sstatic.net/nh63E.png I want my post review button to be displayed after the reviews stars, not in a row. Here is the code s ...

Exploring Concealed Data and Corresponding in jquery, javascript, and html

A unique template contains 2 hidden fields and 1 checkbox. Using the function addProductImage(), the template is rendered and added to the HTML page. To retrieve the values of the hidden fields (thisFile and mainImage) from a dynamically generated div wit ...

Creating a custom Higher Order Component to seamlessly connect react-relay and react-router using TypeScript

Hey there! So, my Frankenstein monster project has decided to go rogue and I'm running out of hair to pull out. Any help would be greatly appreciated. I've been working on setting up a simple app with React, React-Router, React-Relay, and Typesc ...

Guide on personalizing the Material stepper component with labels positioned at the top

I am currently working with the Material Stepper component. While using it, I noticed that the stepper label position is set to left and bottom by default. However, I would like to customize it so that the stepper labels appear at the top and bottom of the ...