0

I have a flask backend api to return a link of picture online, e.g.,

@app.route('/api/pic')
def pic():
    ......
    return jsonify({"pic": "https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png"

and what I want to do is render a page with this picture with reactjs. However, I failed to integrate this with my front-end. Could someone provide a minimal working example to help me out?

John M.
  • 825
  • 1
  • 10
  • 22

1 Answers1

0

Here's an example, assuming you'll be using fetch() in the real world:

import React from "react";
import ReactDOM from "react-dom";

const fakeAPI = val => {
  return new Promise(res => {
    setTimeout(res.bind(null, val), 2000);
  });
};

const fakeFetch = () => {
  return fakeAPI("https://via.placeholder.com/350x150");
};

class App extends React.Component {
  state = {
    image: "",
    loading: true
  };

  componentDidMount() {
    fakeFetch().then(image => {
      this.setState({ image, loading: false });
    });
  }

  render() {
    if (this.state.loading) {
      return <h1>loading</h1>;
    }

    return <img src={this.state.image} />;
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Working example here.

Colin Ricardo
  • 16,488
  • 11
  • 47
  • 80