React.js Axios Example to Make HTTP Get Call to Get Random Photo in Javascript Full Project For Beginners

 

 

Welcome folks today in this blog post we will be using react.js to get random photo using axios to make http get call to the api. All the full source code of the application is shown below.

 

 

 

Get Started

 

 

 

In order to get started you need to make a index.html file and copy paste the following code

 

 

index.html

 

 

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

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.1/umd/react.production.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.1/umd/react-dom.production.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>

 

 

 

script.js

 

 

"use strict";

class AxiosReactExample extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      imageURL: ''
    };
  }

  componentDidMount() {
    axios.get('https://dog.ceo/api/breeds/image/random').then(response => {
      console.log(response.data);
      this.setState({
        imageURL: response.data.message
      });
    }).catch(error => {
      console.log(error);
    });
  }

  render() {
    const {
      imageURL
    } = this.state;
    return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("h1", null, "Axios with React Example"), /*#__PURE__*/React.createElement("h2", null, "How to make API requests in React using Axios"), /*#__PURE__*/React.createElement("img", {
      src: imageURL,
      alt: "dog"
    }));
  }

}

ReactDOM.render( /*#__PURE__*/React.createElement(AxiosReactExample, null), document.getElementById('root'));

Leave a Reply