0
votes

In React I have stored images in different variables like

import Small from '../images/small.png' 
import Medium from '../images/medium.png'

And I store these variables in a data.js file like

const Paper = [{ Head: "<strong>Heading Content</strong>sub-heading", content: ["Small","Medium"] },{ Head: "<strong>Heading Content 2</strong>sub-heading", content: ["Small","Medium"] }...];

Then print this datas in my page Heading are print okay but the the images not showing:

{Head}
{Paper.map((Paper,index) => (
  <div className='news-papper'>
    <img className='images' src={images[index]} alt='ans-img'/>
  </div>
))
}

how to print the image from JSON data in react, I am new in react.

1
What JSON data?evolutionxbox
@evolutionxbox { Head: "<strong>Heading Content</strong>sub-heading", content: ["Small","Medium"] },...manoop m
Quick clarification: That's not JSON.evolutionxbox
That's just a javascript array. JSON is the stringified representation of javascript objects. Anyway in your html snippet i see you are getting the image url from images[index] and you are saying there is no image shown. What is images and how you fill it?Doc
Also, ["Small","Medium"] doesn't store the images. They're only strings in an array.evolutionxbox

1 Answers

0
votes

It's better to have your images in your public folder. If you build your project the folder structure you see during development will no longer exist because everything is bundled and minimized. The only folder that will remain intact is your public folder. If you store your images there you can have a subfolder and access it like so

./<your_subfolder_name>/<your_image.extension>. 

If you use a custom public URL for your app you can also use them like so

`${process.env.PUBLIC_URL}/<your_subfolder>/<your_image.extension>`

Doing this allows you to pass the path directly to your image src attribute.

However, the problem here is your structure. The images array does not exist as I can see and even if it existed your reference to the images is as strings.

You can try a structure like this:

let data = [
 {
   head: <strong>Content without quotation. It's JSX and it can be rendered as 
         it is</strong>,
   imagePath: `${process.env.PUBLIC_URL}/my_image.png`
 }
]