Example of React Bootstrap Datatable

This example display REST Api Data in react bootstrap data-table. This comes with key features of Sort, Filter, Pagination, Custom Labels, Presentational and raw data separation, Custom column sort and column filter function.


Add required dependencies

To create the example project for this example, open command prompt, navigate to a convenient location, and run the command as shown below :

create-react-app example

Now navigate to the project folder and add the React Bootstrap Datatable package to the project as shown below :

cd example
npm i react-bs-datatable

Now add bootstrap to design it responsive.

npm i bootstrap-4-react

Now just replace the placeholder content of App.js with given below content :


src\App.js
import React, { Component } from "react";
import Datatable from "react-bs-datatable"; // Import this package
import "bootstrap/dist/css/bootstrap.css";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      items: []
    };
    this.header = [
      { title: "Name", prop: "name", sortable: true, filterable: true },
      {
        title: "User Name",
        prop: "username",
        sortable: true,
        filterable: true
      },
      { title: "Phone", prop: "phone", sortable: true, filterable: true },
      { title: "Website", prop: "website", sortable: true, filterable: true }
    ];
  }

  componentDidMount() {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then(res => res.json())
      .then(
        result => {
          this.setState({
            isLoaded: true,
            items: result
          });
        },
        error => {
          this.setState({
            isLoaded: true,
            error: error
          });
        }
      );
  }

  render() {
    const { error, isLoaded, items } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      console.log(this.state.items);
      return (
        <div class="container">
          <Datatable
            tableHeader={this.header}
            tableBody={this.state.items}
            keyName="userTable"
            tableClass="striped hover responsive"
            rowsPerPage={3}
            rowsPerPageOption={[3, 5, 8, 10]}
            initialSort={{ prop: "username", isAscending: true }}
          />
        </div>
      );
    }
  }
}
export default App;


Most Helpful This Week