Ayush Srivastava
Ayush Srivastava

Reputation: 27

How to pass a json array in react?

First of all I want to clear this I am using cdn for react and using ajax for fetching the details from the json file.

So,I have a json file reactjs.json which looks like...

[
    {
        "e64fl7exv74vi4e99244cec26f4de1f":[ "image_1.jpg","image_2.jpg"]
    }
]

index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Image Viewer-Static</title>
  </head>

  <body>
    <div id="root"></div>

    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/[email protected]/babel.min.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

    <script type="text/babel">
      class FetchDemo extends React.Component {
        constructor(props) {
          super(props);

          this.state = {
          images: []
          };
        }

        componentDidMount() {
          axios.get('reactjs.json').then(res => {
            console.log(res.data);
            this.setState({ images: res.data });
          });
        }

        render() {
          const { images } = this.state;
          return (
            <div>
              {this.state.images.map((images, index) => (
                <PicturesList key={index} apikeys={images.e64fl7exv74vi4e99244cec26f4de1f} />
              ))}
            </div>
          );
        }

      }

      class PicturesList extends React.Component {
        render() {
          return (
            <img src={this.props.apikeys} alt={this.props.apikeys}/>
            
          );
        }
      }
    
      ReactDOM.render(
        <FetchDemo/>,
        document.getElementById("root")
      );
    </script>
  </body>
</html>

I want to show the image named image_1.jpg,image_2.jpg but this.props.apikeys fetch the value like image_1.jpg,image_2.jpg

images

But I want that it gives two values and show the two image.

I tried a lot to solve this but fails.Any suggestion and help will be welcomed.

Upvotes: 1

Views: 10190

Answers (4)

Varun Suresh Kumar
Varun Suresh Kumar

Reputation: 879

since you already have the json file in the file structure you can just import and use it..

import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
import reactjsJSON from "./reactjs.json";

class FetchDemo extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      images: reactjsJSON
    };
  }

** Edit: **

Your html file

<!DOCTYPE html>
<html>
  <head>
    <title>Image Viewer-Static</title>
  </head>

  <body>
    <div id="root"></div>

    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/[email protected]/babel.min.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

    <script type="text/babel">
        class FetchDemo extends React.Component {
          constructor(props) {
            super(props);

            this.state = {
            images: []
            };
          }

          componentDidMount() {
            axios.get('/reactjs.json').then(res => {
              console.log(res.data);
              this.setState({ images: res.data });
            });
          }

          render() {
            const { images } = this.state;
            return (
              <div>
                {    this.state.images.map(imageObjs =>
        Object.keys(imageObjs).map(key =>
          imageObjs[key].map((image, index) => (
            <PicturesList key={index} apikeys={image} />
          ))
        )
      )}
              </div>
            );
          }

        }

        class PicturesList extends React.Component {
          render() {
            console.log(this.props)
            return (
              <img src={this.props.apikeys} alt={this.props.apikeys}/>

            );
          }
        }

        ReactDOM.render(
          <FetchDemo/>,
          document.getElementById("root")
        );
    </script>
  </body>
</html>

Your JSON, tested for all possibilities, replaced with dummy images

[
  {
    "e64fl7exv74vi4e99244cec26f4de1f": [
      "https://picsum.photos/200?image=2",
      "https://picsum.photos/200?image=2"
    ],
    "e64fl7exv74vi4e99244cec26f4deop": [
      "https://picsum.photos/200?image=2",
      "https://picsum.photos/200?image=2"
    ]
  },
  
  {
    "e64fl7exv74vi4e99244cec26f4de1g": [
      "https://picsum.photos/200?image=2",
      "https://picsum.photos/200?image=2"
    ]
  }
]

serve both the files in same http server and check the output.... since both files are served from same server u can add './' path to fetch and get JSON data...

Upvotes: 0

ileenhow
ileenhow

Reputation: 1

I write a demo in codesandbox: https://codesandbox.io/s/oorn5o162q, you can check it out.

I use two real image urls in json, and refine your component code.

Upvotes: 0

Vishmi Money
Vishmi Money

Reputation: 144

Here you are setting the array [ "image_1.jpg","image_2.jpg"] to apiKeys in

   <PicturesList key={index} apikeys={images.e64fl7exv74vi4e99244cec26f4de1f} />

So when you try to set the image src here

  <img src={this.props.apikeys} alt={this.props.apikeys}/>

what you are setting as this.props.apikeys to src is an array. You have to handle the two images in the array separately to set the source of each image as a String. Try as follows.

        {this.props.apikeys.map((image, index) => (
            <img src={image} alt={image}/>
          ))}

Upvotes: 1

Daniel
Daniel

Reputation: 1

Looks to me like you are receiving this JSON repose & then setting a JSON object into your state. Try looking at

JSON.parse()

. Your also setting the whole JSON object to your images array. You need select a key. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

Upvotes: 0

Related Questions