Reputation: 936
How to pick the local path of image
Json
"avatarUrl": "avt1.jpg"
All the images are under src>img folder. I am looking for absolute path + image name from json.
How I can achieve this reactJs
<img src={require('./img/avt1.jpg')} width="60" />
Package.js
{
"name": "lummdb",
"version": "0.1.0",
"private": true,
"dependencies": {
"moment-timezone": "^0.5.14",
"react": "^16.0.0",
"react-dom": "^16.0.0",
"react-fontawesome": "^1.6.1",
"react-scripts": "1.0.16",
"axios": "^0.17.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
}
Upvotes: 10
Views: 11021
Reputation: 1
Use backticks formatting in the require method then add your json variable name
<img src={require(`${element.avartarUrl}`)}
element
being your json file name or the variable name you used then avartarUrl
is the json variable you stored the image.
Upvotes: 0
Reputation: 1
Hy, my solution:
JSON object
"url": "../assets/image/name.png"
Specify a path relative to the public folder
Component
<img className="classNames" src={'${url}'} alt="AltImage" />
or
src={url}
Works so and so. Good luck!
Upvotes: 0
Reputation: 81
Move all of your images to the public/images
.
JSON file:
{
"title": "something",
"image_link": "../images/yourfilename1.jpg"
},
{
"title": "something2",
"image_link": "../images/yourfilename2.jpg"
}
CardComponent:
const InfoCard = ({image_link, title}) => {
return (
<div>
<h3>{title}</h3>
<img src={image_link} alt={title} />
</div>
)
}
export default InfoCard;
Upvotes: 7
Reputation: 93163
Seems you are using create-react-app , try to add NODE_PATH=src
in your environment variable , or append it to script alias
"start": "NODE_PATH=src react-scripts start",
If you are done, you can do the following :
<img src={require('img/avt1.jpg')} width="60" />
Then, if you are getting the name of image from json dynamically :
<img src={require(`img/${avatarUrl}`)} width="60" />
If does not work, consider to export NODE_PATH before :
export NODE_PATH=src;
npm start;
Upvotes: 7