0

Im building a grid which consists of Items with ul li structure. Im using the JSON fetched data as a prop for the Class, everything else is fetched but the image. The problem is I cant dynamically fetch my images to the list for the Items from a JSON file. The img files are in a subfolder of the JSON folder. So the path doesn't do anything for me. Every Item has a different image.

[
{
"path": "./imgs/doglogo.svg"
"name": "dog"
},
{
"path": "./imgs/catlogo.svg"
"name": "cat"
}
]

I think I need some sort of required root path parameter but have no idea how to do this?

return (
    <li className={'grid-item'}>
        <a href={href} className={gridItemLink} key={name}>
            <div className={'grid-image'}>
                <img src={path} img alt="" />
            </div>
        </a>
    </li>
);  
Omar
  • 7
  • 5
  • The path should be relative to your component. With the way paths are defined in your json, it would mean that the images folder is in the same directory as this component, which doesnt seem right. – Chris Ngo Jun 19 '19 at 09:11
  • @ChristopherNgo at runtime, I think the browser will indeed look for the images in that relative path, e.g. if this application is hosted at `locahost:8080/myapp`, the browser will try to load the `dog` image from `locahost:8080/myapp/imgs/doglogo.svg`. Does your app serve the images at that path? – mehmetseckin Jun 19 '19 at 09:14

1 Answers1

0

Unfortunately, you have to import images in order to use them.

  1. If you have used create-react-app to create your project, you can put the images in the public folder (more information see Correct path for img on React.js):
<img src={path} />
  1. If you are using webpack, another option would be to require the image path with template literals (see Load images based on dynamic path in ReactJs for more information):
<img src={require(`${path}`)} />
wfreude
  • 492
  • 3
  • 10