React not displaying images with relative paths

In the past, I used to import images in React like this:

import person from '../images/image1.png'

And then use them in my code like this:

<img src={person} alt="" />

Now, for some reason, I want to directly specify the image path in the src, like so:

<img src="../images/image1.png" alt="" />

However, it doesn't seem to work as expected.

Answer №1

When it comes to adding images in your JSX using Create React App, there are two different methods you can utilize. The first approach involves utilizing the import statement to import an image located within the src folder. Here's an example:

import person from '../images/image1.png'
<img src={person} alt="" />

The second method requires specifying the path of the image directly to the src attribute of the <img> tag. However, this path should always be relative to the public folder and must start with /, where / represents the public folder itself.

To learn more about adding images, fonts, and files, refer to the documentation on Adding Images, Fonts, and Files and Using the Public Folder available on Create React App's official website.

In order for the second method to function correctly, consider placing the images folder inside the public directory and accessing your images in the following manner:

<img src="/images/image1.png" alt="" />

If your React application is going to be deployed in a subfolder, you may need to specify the homepage in your package.json file as

"homepage":"www.example.com/folder"
. Additionally, make use of process.env.PUBLIC_URL as shown below to ensure the correct path for your images.

<img src={process.env.PUBLIC_URL + "/images/image1.png"} alt="" />

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

Transmit a JSON object while simultaneously receiving the corresponding response

As part of a school project, I need to work with JSON. The server will process the file and send back a response in JSON format. This entire exchange needs to be done using JavaScript. I recently learned about the XMLHttpRequest object, but I'm still ...

How PHP Processes Fragment Identifiers within URLs

Looking for some advice from the community on a tricky situation I'm facing. Here's the issue at hand: I have developed a website with dynamic content pulled via AJAX and displayed using JS. To allow direct links to my content, I modify the frag ...

steps to invoke a class within a function

I'm currently attempting to invoke a model class from the Axios response. Instead of displaying an alert, I would like to show a modal popup. Can someone assist me with how to call the modal class from the Axios interceptor function? Thank you in adva ...

What is the process for inserting or removing a row with Javascript?

Currently, I am in the process of working on some HTML/PHP code which is displayed below. <h3 style="text-align:center;margin-top:45px;">Sitting Days</h3> <div class="sitting-days" style="display:flex; justify-content:center; margin-bottom ...

I'm experiencing unexpected behavior with the <form> element in React, it's not functioning as I

I have encountered a strange behavior while trying to implement a form element for user input. When I directly insert the form element, everything works perfectly fine as I type in the letters. However, if I insert the form element through the AddForm comp ...

What is the best method to iterate through a jQuery array variable without any errors?

I am struggling with a PHP project where I need to create a json array of data values that will be used in a jQuery script. The array looks something like this: [3,94,83,141]. My goal is to leverage these values to manipulate the visibility of rows in a ta ...

What are the most effective strategies for receiving and subscribing to push notifications from a RabbitMQ server?

Utilizing the microservices architecture with NestJs, I have developed two separate applications. The main application operates on port 9000 while the Notification service functions on ports 9001 in amqp and http protocols. I have successfully initiated n ...

Having trouble executing "npm install" following the clone from GitHub in React

After cloning a repository from GitHub, I attempted to run "npm install" but encountered the following error: https://i.sstatic.net/QM4RZ.png Since the project is still in development, should I install or add anything else to successfully run it? ...

Formatting dates in Angular 2 and handling them in MongoDB with Express

I am currently working with Angular 2 and ExpressJS along with MongoDB. I have a date format that is being retrieved as 2016-06-02T14:20:27.062Z, but I need to display it in the format 06/02/2016 14:20:27 Express: In models/user.js: var userSchema = Sch ...

How to Prompt CSS Rule Evaluation to Ensure Proper Functionality (Solution)

When encountering the issue of browsers, specifically Internet Explorer in my case, failing to correctly implement complex CSS rules, is there a way to force the evaluation? For example: body[data-some-flag="3"] #someElement .someClass svg stop:first-chi ...

Segment the progress bar into sections

Struggling with an Angular app, and still new to HTML and CSS, I am attempting to create a unique progress bar. I aim to split each section of the progress bar into two subsections with distinct background colors shown in this image: https://i.sstatic.net/ ...

A guide on utilizing React hooks to randomly divide a group into two teams

Is there a way to randomly divide players from an array into two teams, ensuring that each team has an equal number of players if the total is even. If it's an odd number, having one extra player in either team is acceptable. I have written a JavaScr ...

What is the best way to find the vertex positions of a JSON model in

Here is the code I am using to load a 3D model in THREE.js: var noisenormalmap = THREE.ImageUtils.loadTexture( "obj/jgd/noisenormalmap.png" ); noisenormalmap.wrapS = THREE.RepeatWrapping; noisenormalmap.wrapT = THREE.RepeatWrapping; noisenormalmap.repeat. ...

How can we ensure that the form inputs in React retain the data of the clicked element when being updated?

I'm currently facing a challenge in updating data within my React component. While the update functionality is working, I want to enhance the user experience by pre-filling the form inputs with the current state of the data before making any updates. ...

A guide to dynamically extracting values from JSON objects using JavaScript

I have a JSON array with a key that changes dynamically (room number varies each time I run the code). My goal is to access the inner JSON array using this dynamic key. Here's what I've attempted so far, but it's throwing an error. Here is ...

Display only the content that is within the container and visible

Within this demonstration, there are 2 divs present - one containing the text t, and the other containing the text s. Both of these divs are enclosed within the .items container. As it stands currently, both divs are visible. However, my goal is to modify ...

Is it possible to retrieve text from various iframes using the rangy library?

Here's a question that follows up on a problem I've been having with grabbing selected text from iframes using rangy. The code works well for the first iframe, but when I try to grab elements from multiple iframes using the same button, it doesn& ...

What is the best way to implement conditional hook usage in React?

Having two hooks at my disposal, useLocalStorage and useQuery, I find myself wondering about conditionally utilizing one of them based on an input prop. I'm considering writing the following: const [value, setValue] = localStorage ? useLocalStorage() ...

JQuery syntax for adding a comma before the first element in an array

When I insert data into an array, the output in my console includes a comma before the first element (9). How can I remove this comma from the first element using the provided code snippet? ,9,My firstname,My lastname,<a href="/cdn-cgi/l/email-protecti ...

The loop feature in Swiper.js seems to be malfunctioning and not functioning as

I'm currently in the process of setting up a carousel using swiper.js and here is my setup: { slidesPerView: 1, slidesPerColumn: 1, initialSlide: this.initialSlide, loop: true } As expected, I'm encountering an issue where dupl ...