I have an object(user.js), App.js and an image(admin.png) in the same directory.
user.js
export const user = {
name: 'ADMIN',
logo: './a.png'
}
Inside App component, I am trying to access the image, but it’s not working.
App.js
import { user } from './user.js'
function App() {
return (
<div>
<h1>{user.name}</h1>
<img src={user.logo} height={20} width={20} />
</div>
);
}
2
Answers
When you specify a relative path in the user.js file, it’s treated as a regular string, not as a module import, so the path won’t work as expected when using create-react-app or similar setups. Here’s how to correctly handle the image import:
Import the Image Explicitly:
Instead of specifying the image path as a string in your user.js, you should import the image directly in App.js. This way, Webpack or your build tool can resolve the path correctly.
Here’s how you can modify your files:
user.js
App.js
Using require (Alternative Approach):
If you want to keep the image path in user.js, you can dynamically require the image in App.js:
user.js
App.js
In this alternative approach, require dynamically loads the image based on the path specified in the user object.
Both methods will ensure that the image is correctly loaded and rendered in your React application. The first method is generally preferred for its simplicity and clarity.
1. Try to directly import the Image in user.js: Since you’re using create-react-app or similar, you need to import the image file directly in user.js instead of using a string path.
2. In App.js, use the code as is: