Home > Software engineering >  How can I put a JSON object into JSX?
How can I put a JSON object into JSX?

Time:07-22

I have a json array that contains some information :

 [
      {
        
        "id": 1,
        "imageUrl": "./img1.png",
        
      },
      {
      
        "id": 2,
        "imageUrl": "./img2.png",
        
        
      }
    ]

I tried to make a class in which the elements were sorted and added the necessary link to the src, but the information from JSON is not put into JSX.

class Paintings extends Component  {
  render(){
      return(
          <ul>
              {
                paintings.map((s) => {
                  return (  
                    <div>
                    <img src={s.imageUrl} alt={s.id} />
                 </div>
                  )  
                    })  
                  }
              </ul>
      )
  
  

CodePudding user response:

The question is more general then just about images here. It is to import and loop a JSON object in JSX.

You have some syntax error in your code, I fixed them and shared an online editor implementation for you to have a look as well.

Save your json in a file and import that file in your react code then map the json object.

For the images location, although this is not the recommended method, I think you should put your images under public folder and make sure you have your json file with the correct path.

Sample JSON file I have structured, for your reference:

[
  {
    "id": 1,
    "imageUrl": "image1.png"
  },
  {
    "id": 2,
    "imageUrl": "image2.png"
  }
]

Then you should be able to use below code to be able to generate it.

import React, { Component } from "react";
import Painting from "./Painting";

class Paintings extends Component {
  render() {
    return (
      <ul>
        {Painting.map(({ id, imageUrl }) => (
          <div key={id}>
            <img src={imageUrl} alt={id} />
          </div>
        ))}
      </ul>
    );
  }
}

export default Paintings;

Here is a basic implementation for you to check out, we are able to map and see the items. I have added some sample images and please pay attention to json file and how its ready to map the JSX image objects based on the file paths.

https://codesandbox.io/s/react-json-into-jsx-19gj1w

  • Related