React.js JSONPlaceholder API Example to Render Data inside Table Full Example Tutorial

React.js JSONPlaceholder API Example to Render Data inside Table Full Example Tutorial

 

Welcome folks today in this tutorial we will be looking at a basic example of react.js where we will be rendering dynamic data coming from jsonplaceholder api to a table. All the source code of the tutorial is given below. A step by step youtube video is also shown below.

 

x
React.js JSONPlaceholder API Example to Render Data inside Table Full Example Tutorial For Beginners video
 

Get Started

 

Just create a new react.js project and inside your app.js file write the following code to it.

 

import React, { Component } from 'react'

class Table extends Component {
  constructor(props) {
    super(props)
    this.state = {
      users: [],
      isLoading: false,
      isError: false
    }
  }
}

 

 

Here we have declared a simple table component inside which we have three state variables namely the users,isLoading and isError.

Now we will be making the componentDidMount which will execute as soon as the component is ready to be there inside the application.

 

async componentDidMount() {
    this.setState({ isLoading: true })
    const response = await fetch('https://jsonplaceholder.typicode.com/users')
    if (response.ok) {
      const users = await response.json()
      this.setState({ users, isLoading: false })
    } else {
      this.setState({ isError: true, isLoading: false })
    }
  }

 

 

Here we are using this function as a async function because we are making a get request to the jsonplaceholder api and the result which is returned from the api will take some time so we have used the keyword await inside it. So this needs to be a async function. And now after the data is returned we are setting the state variables accordingly. If any error takes place then also we are handling it successfully.

READ  React.js Hooks Random Password Generator and Manager UI with Icons in Browser Using Vanilla Javascript Full Project For Beginners

 

render() {
    const { users, isLoading, isError } = this.state

    if (isLoading) {
      return <div>Loading...</div>
    }

    if (isError) {
      return <div>Error</div>
    }

    return users.length > 0
      ? (
        <table>
          <thead>
            <tr>
              {this.renderTableHeader()}
            </tr>
          </thead>
          <tbody>
            {this.renderTableRows()}
          </tbody>
        </table>
      ) : (
        <div>
          No users.
      </div>
      )
  }

 

 

So now we are rendering out the data which is coming from the api and we have stored this data inside the state variables and now we need to render this data with the help of table. So now in this block of code we are first of checking if the length of the array is greater than 0 then only proceed and inside it we have declared two custom functions which we will write in the next step.

 

renderTableHeader = () => {
    return Object.keys(this.state.users[0]).map(attr => <th key={attr}>{attr.toUpperCase()}</th>)
  }

 

 

So in this block of code we are looping through the first row and we are printing all the header rows of the table.

 

 

renderTableRows = () => {
    return this.state.users.map(user => {
      return (
        <tr key={user.id}>
          <td>{user.id}</td>
          <td>{user.name}</td>
          <td>{user.username}</td>
          <td>{user.email}</td>
          <td>{`${user.address.street}, ${user.address.city}`}</td>
          <td>{user.phone}</td>
          <td>{user.website}</td>
          <td>{user.company.name}</td>
        </tr>
      )
    })
  }

 

 

READ  Build a React.js Pixel Art Text Generator in Browser Using HTML5 CSS3 and Javascript Full Project For Beginners

So now inside this method we are looping all the array which is passed to it and we are displaying all the rows of the table with all the properties which are specified namely name,username,email and phone etc.

 

 

 

 

 

Leave a Reply