React - load new image - error

In summary, the conversation involves a person seeking help in changing the logo for a web application they are working on using React. They have encountered an error when trying to import the new logo from the public folder. After trying different methods, they still cannot get the new logo to appear on the application. The expert suggests deleting a line of code and checking the image path, but the issue still persists.
  • #1
mathmari
Gold Member
MHB
5,049
7
Hey! :smile:

I need some help in react.
I have a code for a web application and I want to change the logo. The logo I want to use is in the public folder, in this folder there is also a favicon with the old image. In the src folder there is a folder images with the old image. In the src folder there is also the Logo.js file. In that I have written the following :

Code:
import { useTheme } from '@mui/material/styles';
 
import logo from '/logo.png';
 
const Logo = () => {
    const theme = useTheme();
 
    return (
        <img src="%PUBLIC_URL%/logo.png" alt="abc" width="100" />
 
    );
};
 
export default Logo;

I get an error because of '/logo.png'. I have tried this also with '../../public/logo.png' but I get again an error. How is the correct way to load the new logo? 🤔
 
  • Like
Likes I like Serena
Technology news on Phys.org
  • #2
What does the error message say?
 
  • Like
Likes mathmari
  • #3
FactChecker said:
What does the error message say?

WIth the command

import logo from '/logo.png';

I get the following error :

Compiled with problems:

ERROR in ./src/ui-component/Logo.js 14:0-29

Module not found: Error: You attempted to import /logo.png which falls outside of the project src/ directory. Relative imports outside of src/ are not supported. You can either move it inside src/, or add a symlink to it from project's node_modules/.

What is the correct way to do that?
 
  • #4
Hey @mathmari!

Have you tried to make it just 'logo.png'?

The leading '/' indicates it should come from some root directory that is considered "unsafe". Instead it should probably just come from whatever directory is considered the top level directory where all resources are expected. You may need to move the file there, whichever directory that is. 🤔

On the other hand, you are not actually usuing the logo that you are importing, so perhaps there is no need to import it at all? Instead the file should just be at the expected location. 🤔
 
  • Like
Likes FactChecker and mathmari
  • #5
I like Serena said:
Hey @mathmari!

Have you tried to make it just 'logo.png'?

The leading '/' indicates it should come from some root directory that is considered "unsafe". Instead it should probably just come from whatever directory is considered the top level directory where all resources are expected. You may need to move the file there, whichever directory that is. 🤔

On the other hand, you are not actually usuing the logo that you are importing, so perhaps there is no need to import it at all? Instead the file should just be at the expected location. 🤔

When I write just 'logo.png' I get the following error:

Compiled with problems:

ERROR in ./src/ui-component/Logo.js 14:0-28

Module not found: Error: Can't resolve 'logo.png' in 'C:\Users\...\new-frontend-main\src\ui-component'

🤔
 
  • #6
mathmari said:
When I write just 'logo.png' I get the following error:
Ah right... you are trying to import `logo.png` as if it is a source code module, but it is not.
How about deleting line 3 altogether? 🤔
 
  • Like
Likes mathmari
  • #7
I like Serena said:
Ah right... you are trying to import `logo.png` as if it is a source code module, but it is not.
How about deleting line 3 altogether? 🤔

This works! I don't get any errors now. But the picture is not shown. Only 'abc' is shown that we get from
<img src="%PUBLIC_URL%/logo.png" alt="abc" width="100" />

What do I wrong with the image? 🤔
 
  • #8
mathmari said:
This works! I don't get any errors now. But the picture is not shown. Only 'abc' is shown that we get fromWhat do I wrong with the image?
Apparently the image file is not where it is expected.
If you right click on the image and select Inspect, what does it show for its `src` path? 🤔
 
  • Like
Likes mathmari
  • #9
I like Serena said:
Apparently the image file is not where it is expected.
If you right click on the image and select Inspect, what does it show for its `src` path? 🤔

You mean at the side bar of Visual Studio Code I shall cright click on the name of the image?
When I copy the path I get : new-frontend-main\public\logo.png

Or do you mean somewhere else to right click? 🤔
 
  • #10
mathmari said:
You mean at the side bar of Visual Studio Code I shall cright click on the name of the image?
When I copy the path I get : new-frontend-main\public\logo.png

Or do you mean somewhere else to right click?
The code is for a web application, so the resulting code should be viewable with a browser. When you wrote that you could not see the picture, I assumed that you could not see it in a browser. Is that the case? 🤔
If so, then I meant the right click on it in the browser.
 
  • #11
I like Serena said:
The code is for a web application, so the resulting code should be viewable with a browser. When you wrote that you could not see the picture, I assumed that you could not see it in a browser. Is that the case? 🤔
If so, then I meant the right click on it in the browser.

When I right click in the browser it says that the loading of the image is not possible. What am I doing wrong? 🤔
 
  • #12
mathmari said:
When I right click in the browser it says that the loading of the image is not possible. What am I doing wrong?
It should be possible to right click and select inspect element. That should show a list of tab sheets and one of them shows the elements. We should see more information there. In particular we want to know from which path it tried to load the image.
 
  • Like
Likes mathmari
  • #13
I like Serena said:
It should be possible to right click and select inspect element. That should show a list of tab sheets and one of them shows the elements. We should see more information there. In particular we want to know from which path it tried to load the image.

We have the following:

1664569405204.png


When I click on "event" we see :

1664569461242.png


🤔
 
  • #14
It shows that it expects the image at %PUBLIC_URL%/logo.png, which is not a valid path. The %PUBLIC_URL% is not expanded. It should have been replaced on the server side somehow. You might try to just leave it out completely, or otherwise replace it by a path to where the image actually is.
 
  • Like
Likes mathmari
  • #15
I like Serena said:
It shows that it expects the image at %PUBLIC_URL%/logo.png, which is not a valid path. The %PUBLIC_URL% is not expanded. It should have been replaced on the server side somehow. You might try to just leave it out completely, or otherwise replace it by a path to where the image actually is.
There is no server side (unless you are building for Next.js). %PUBLIC_URL% should be replaced in the build stage by create react app, although you often don't need it at all.

Here is a guide to achieving what you want: https://create-react-app.dev/docs/adding-images-fonts-and-files/

PhysicsForums is not a great place to look for front-end framework advice (unless it's for Vue of course :cool:)
 
  • Informative
Likes I like Serena
  • #16
JavaScript:
import { useTheme } from '@mui/material/styles';

// This is wrong: you are trying to import from the filesystem root!
// import logo from '/logo.png';
// Instead you want:
import logo from './logo.png';
// Or even better keep your logo.png file in a subfolder of ./src and (assuming the current
// file is src/ui-component/Logo.js) use:
import logo from '../assets/img/logo.png';
 
const Logo = () => {
    const theme = useTheme();
 
    return (
        // This is wrong - logo.png is a literal string here:
        <img src="%PUBLIC_URL%/logo.png" alt="abc" width="100" />
        // Instead write {logo} to refer to the imported file as a template variable:
        // Edit: the following line was originally posted with "{logo}" in quotes which was wrong.  
        <img src={logo} alt="abc" width="100" />
    );
};
 
export default Logo;
 
Last edited:
  • Like
Likes mathmari and I like Serena
  • #17
We have the following files:

1664612151962.png


I created a folder and called it img and moved the png file there but I still don't get the image as a result.

Why do I not see the image at the browser? What is wrong? 🤔
 
  • #18
mathmari said:
Why do I not see the image at the browser? What is wrong?
Which code did you use now? 🤔

What does Inspect element show in the browser now as the src path of the <img> element? 🤔
 
  • Like
Likes mathmari
  • #19
I like Serena said:
Which code did you use now? 🤔

What does Inspect element show in the browser now as the src path of the <img> element? 🤔

I created a folder img and moved the logo.png there and I used the code:

Code:
import { useTheme } from '@mui/material/styles';
import logo from './assets/img/logo.png';
 
const Logo = () => {
    const theme = useTheme();
 
    return (
        <img src="{logo}" alt="abc" width="100" />
    );
};
 
export default Logo;

At the Inspect I get :

1664613366149.png
What does that mean? 🤔
 
  • #20
The text {logo} has not been expanded. I'm not sure why. Which command did you use to build and run the web application? 🤔

Suppose you add console.log(logo) after line 2 as shown in the example that @pbuk pointed out. What do you get in the logging then? You can see the logging if you right click, select Inspect, and select the Console tab sheet. 🤔

You might try to replace {logo} in line 8 by logo.png, or perhaps /assets/img/logo.png to see if the image will show up then. 🤔
 
  • Like
Likes mathmari
  • #21
Sorry, {logo} should not be in quotes in my post
 
  • Like
Likes I like Serena and mathmari
  • #22
Now I have seen your file layout everything changes. We can use the method described in https://create-react-app.dev/docs/using-the-public-folder (with the disadvantages noted there).
JavaScript:
// You are not using anything from the theme so there is no need to import it.
// import { useTheme } from '@mui/material/styles';

// You don't need to import a file that is in `public`.
// import logo from '/logo.png';
 
const Logo = () => {
    // You are not using this so delete it (your lint tool should have warned about this).
    // const theme = useTheme();
    return (
        <img src="%PUBLIC_URL%/logo.png" alt="abc" width="100" />
    );
};
 
export default Logo;
In other words, just this.
JavaScript:
const Logo = () => {
    return (
        <img src="%PUBLIC_URL%/logo.png" alt="abc" width="100" />
    );
};
 
export default Logo;

Keep the image file at public/logo.png.
 
Last edited:
  • Like
Likes mathmari
  • #23
However you can also do this, described at https://create-react-app.dev/docs/adding-images-fonts-and-files, which has advantages (notably if logo.png is small enough it will be inlined instead of referenced which makes your site load faster).
Code:
# Set up your files like this
assets/img/logo.png
src/ui-component/Logo.js
Now write your component as:
JavaScript:
// Not sure if you need this but it is in the boilerplate in the docs.
import React from 'react';
// We need a relative reference from the location of this file.
import logo from '../assets/img/logo.png';

function Header() {
  return <img src={logo} alt="Logo" />;
}

export default Header;
 
  • Like
Likes mathmari
  • #24
For those of you not familiar with modern JavaScript front-end frameworks thinking "what on Earth is going on here", a brief explanation. Look up the italicised words to delve deeper.

Modern front-end frameworks use a module bundler to turn the code you write into a bundle of assets that are deployed as the application. The code you write is mainly JavaScript (or TypeScript), but the module bundler has plugins that let you work with files that are not JavaScript (e.g. CSS and image files), and also plugins that let you write code in other syntaxes (e.g. JSX or TypeScript) that is transpiled by the plugin into JavaScript.

The most common module bundler is currently Webpack and here we are using two Webpack plugins that are included in the build tool default configuration for the framework we are using here, React:
  • an image loader plugin that realizes that when you type
    JavaScript:
    import logo from '../assets/img/logo.png';
    you are referring to an image file and so it creates the variable logo as an object with an appropriate toString() method yielding a URI. The plugin also tells Webpack to add the referenced file to its list for copying into the distribution bundle (unless the image is small and the plugin has created a data URI for inlining).
  • a transpiler plugin for the template language that is normally used with React, JSX. The transpiler converts
    JavaScript:
    return <img src={logo} alt="Logo" />;
    into valid JavaScript: this could be something like
    JavaScript:
    return `<img src=${logo} alt="Logo" />`;
    but it is actually more complicated than that: lookup the JSX documentation if you are interested.
 
Last edited:
  • Like
Likes mathmari

1. How can I load a new image in React?

To load a new image in React, you can use the "img" tag and set its "src" attribute to the path of the new image file. Alternatively, you can also use the "style" attribute and set the "backgroundImage" property to the path of the new image file.

2. Why am I getting an error when trying to load a new image in React?

There could be several reasons for getting an error while loading a new image in React. Some common reasons include incorrect file path, incorrect syntax, or missing image file. Make sure to double-check your code and the path of the image file to resolve the error.

3. How can I handle errors while loading new images in React?

You can use the "onError" event handler on the "img" tag to handle errors while loading new images in React. This event will be triggered if the image fails to load, and you can then display a default image or an error message to the user.

4. Can I dynamically load images in React?

Yes, you can dynamically load images in React by setting the "src" attribute or the "backgroundImage" property to a variable or a state value. This allows you to change the image dynamically based on user input or other conditions.

5. How can I optimize image loading in React?

To optimize image loading in React, you can use lazy loading techniques such as using the "loading" attribute, which allows the browser to prioritize essential content and load images later. You can also use libraries like React Lazy Load or Intersection Observer API to improve performance by loading images only when they are visible in the viewport.

Similar threads

  • Programming and Computer Science
Replies
32
Views
2K
  • Programming and Computer Science
Replies
8
Views
198
  • Programming and Computer Science
Replies
4
Views
4K
  • Programming and Computer Science
Replies
5
Views
3K
  • Programming and Computer Science
Replies
9
Views
3K
  • Engineering and Comp Sci Homework Help
Replies
15
Views
4K
  • Engineering and Comp Sci Homework Help
Replies
8
Views
12K
Replies
6
Views
2K
  • Beyond the Standard Models
Replies
18
Views
3K
Back
Top