1

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.

1
  • Can you provide us, how can you access an image from your link? src expects a public URL valid, like http://www.example.com/image.png Commented Feb 21, 2019 at 9:57

4 Answers 4

1

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}/>
          ))}
Sign up to request clarification or add additional context in comments.

Comments

0

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

4 Comments

I am using cdn so how can I import the json file?@varun
do you get JSON data from external API?
stackoverflow.com/a/45424256/9265743 check this link to add json using javascript
I have a file name reactjs.json which I am using to get the data @Varun
0

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

1 Comment

I am not understanding can you please brief it. I just want that I get the two separate values so that two image will be come on the screen @Denial
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.