article

Sunday, August 29, 2021

ReactJS API Call Json

ReactJS API Call Json

In this tutorial we will show how to call API in ReactJS. The API calls are made to get data and render into application.

src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
public/index.html
//public/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" crossorigin="anonymous">
    <title>ReactJS - API Call</title>
  </head>
  <body>
    <div id="root"></div>
</body>
</html>
src/App.js
//src/App.js
import React, {Component} from 'react';
import User from './user';

class App extends Component {

    state = {
      user: []
    };
    //componentDidMount() method  is called immediately when component mounted and the API call made in this method using fetch method
    //fetch method make GET request to API and parse the response into json using res.json()
    componentDidMount() {
        fetch('http://jsonplaceholder.typicode.com/users')
            .then(res => res.json())
            .then((data) => {
                this.setState({ user: data })
            })
            .catch(console.log)
    }

    render() {
      return (
          <User user={this.state.user} />
      )
    }
}

export default App; 
src/user.js
//src/user.js
import React from 'react'

const User = ({user}) => {
    return (
        <div>
            <center><h1>API Call Json- User List</h1></center>
            {user.map((emp) => (
                <div class="card">
                    <div className="card-body">
                        <h5 className="card-title">{emp.name}</h5>
                        <h6 className="card-subtitle mb-2 text-muted">{emp.email}</h6>
                        <p className="card-text">{emp.company.catchPhrase}</p>
                    </div>
                </div>
            ))}
        </div>
    )
};

export default User

Related Post