How to fetch the URL in React.js application

In this post, I will explain how to create a react application and how to fetch the URL in React.js application. We are going to create a single page app using React.js for this we will use Create-React-App project to set everything set up.

How to fetch the URL in React.js application with example by Anil  Kumar Panigrahi

How to fetch the URL in React.js application with example by Anil Kumar Panigrahi

Create a New React App:

Earlier I have explained how to create Node.js and how to deploy. Now for React.js We need to run the below command to create an app

npm create-react-app anillabs-fetch-demo

This will take a few mins and will create a working directory in the specific folder.

cd anillabs-fetch-demo
npm start

then a basic screen will appear. Under: 3000 port.
Access the sample application in the browser

http://localhost:3000

App Folder structure:

node_modules
public
src
package.json
package-lock.json
README.md

If we want to edit the application then open src/App.js file.
With the above step successfully created React app. Now we will check for fetch the URL and display those data into the page.

Create a new file: AppConst.js

this file is for all constant variables in one place

const AppConstants = {
    API: 'https://randomuser.me/api/?results=30',
    TITLE: 'Anil Labs - React fetch Application',
  }
export default AppConstants

randomuser.me is used for some random profile data generated URL.

In the App.js file, insert the below line

import AppConst from './AppConst';

Under constructor add below code to declare the variables

  constructor(props) {
    super(props);
    this.state = {
      pictures: [],
      isLoading: false
    };
  }

If we want to fetch function then we need to install fetch node_modules

npm install node-fetch --save

after install module then edit App.js

componentDidMount() {
    document.title = AppConst.TITLE;
    this.setState({ isLoading: true });
   
    fetch(AppConst.API)
      .then(response => response.json())
      .then(data => this.setState({ pictures: data.results, isLoading: false }));
  }

display those images in the below code in render

render() {
    const { pictures, isLoading } = this.state;
    if (isLoading) {
      return (<p>Loading ...</p>);
    }

    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <p>Anil Labs - React fetch Application.</p>
          </header>
          <div className="mainBlock">
          <p>  <br /> Fetch data from {AppConst.API} </p>
            <ul>
              {pictures.map(pic =>
                <li key={pic.email}>
                  <img src= {pic.picture.medium} alt="profile pic" />
                </li>
              )}
            </ul>
            <br />
           
          </div>
         
      </div>
    );
  }

After done with these changes we will get the all images with fetch.

Below is complete code for App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import AppConst from './AppConst';


class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      pictures: [],
      isLoading: false
    };
  }
  componentDidMount() {
    document.title = AppConst.TITLE;
    this.setState({ isLoading: true });
   
    fetch(AppConst.API)
      .then(response => response.json())
      .then(data => this.setState({ pictures: data.results, isLoading: false }));
  }
  render() {
    const { pictures, isLoading } = this.state;
    if (isLoading) {
      return (<p>Loading ...</p>);
    }

    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <p>Anil Labs - React fetch Application.</p>
          </header>
          <div className="mainBlock">
          <p>  <br /> Fetch data from {AppConst.API} </p>
            <ul>
              {pictures.map(pic =>
                <li key={pic.email}>
                  <img src= {pic.picture.medium} alt="profile pic" />
                </li>
              )}
            </ul>
            <br />
           
          </div>
         
      </div>
    );
  }
}

export default App;

We can modify the CSS in App.css file, In this example, I have updated few styles. We can check it below.

li{
  float:left;
  list-style-type: none;
 
  padding:10px;
  border-right:1px solid #3687AF;
  background-color: #015287;
  background-repeat: no-repeat;
  background-position: center 30px;
  }
.mainBlock{
  margin: auto;
  width: 75%;
  padding: 10px;
}

After done with all these changes then run below command (which was mentioned earlier in this post)

npm start

Anil Kumar Panigrahi

With more than 10 years experience in PHP and Founder of Anil Labs, a blog for PHP and related posts. contributed posts regarding CodeIgniter, CakePHP and Learn PHP online ... Contact : [email protected]

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.