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"
},
}
To display an image from a local path in React: Download the image and move it into your src directory. Import the image into your file, e.g. import MyImage from './thumbnail. webp' . Set the src prop of the image element to the imported image, e.g. <img src={MyImage} alt="horse" /> .
To fetch image from API with React, we can use the fetch function. We call fetch with the imageUrl to make a GET request to it. Then we call res. blob to convert the response object to a blob.
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;
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With