PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 23, 2022

[FIXED] How can I put a JSON object into JSX?

 July 23, 2022     attributes, image, javascript, json, reactjs     No comments   

Issue

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>
      )
  
  

Solution

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



Answered By - takobaba
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing