Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get local image path from json in react

Tags:

reactjs

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"
  },
}
like image 445
faisaljanjua Avatar asked Nov 11 '17 18:11

faisaljanjua


People also ask

How do I reference a local image in React?

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" /> .

How do I fetch images from API in React?

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.


2 Answers

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;
like image 104
Abdennour TOUMI Avatar answered Sep 20 '22 00:09

Abdennour TOUMI


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;
like image 23
user14777074 Avatar answered Sep 21 '22 00:09

user14777074