9

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"
  },
}
faisaljanjua
  • 886
  • 2
  • 13
  • 28

3 Answers3

7

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;
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
5

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;
simmer
  • 2,639
  • 1
  • 18
  • 22
user14777074
  • 61
  • 1
  • 1
0

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!