Stfvns
Stfvns

Reputation: 1041

How to use Datatable in Reactjs when the data from API

I already parsing API using axios. After that I got the value then I adding to properties Data in Datatable but still not working. The value not parse to Datatable. When I console.log the data is showing. I am use API from https://jsonplaceholder.typicode.com/users.

And hear is my code:

import "./css/jquery.dataTables.css";
import React, { Component } from "react";
import axios from "axios";

const $ = require("jquery");
$.Datatable = require("datatables.net");


export default class Tbl extends Component {
     constructor(props) {
         super(props);
         this.state = {
             users: [],
             loading: true,
         };
     }

     //option 1
     async getUsersData() {
         const res = await axios.get("https://jsonplaceholder.typicode.com/users");
         console.log(res.data);
         this.setState({ loading: false, users: res.data });
     }

    //option 2
     async getUsersData1() {
         const res = await axios.get("https://jsonplaceholder.typicode.com/users");
         return res.data;
     }

     componentDidMount() {
        //call option 1
        this.getUsersData();

         this.$el = $(this.el);
         this.$el.DataTable({
             data: this.state.users, //option 1
             data: this.getUsersData1(), //option 2
             columns: [
                 { title: "Name", data: "name" },
                 { title: "Username", data: "username" },
                 { title: "Email", data: "email" },
                 { title: "Phone", data: "phone" },
                 { title: "Website", data: "website" }
             ],
         });
     }

     componentWillMount() {}

     render() {
         return (
             <table className="display" width="100%"
                 ref={(el) => (this.el = el)}>
             </table>
         );
     }
}

I already try for option 1 and option 2 but still not working.

Thank,

Upvotes: 0

Views: 13833

Answers (2)

Aman Mehra
Aman Mehra

Reputation: 195

Use the "react-data-table-component" library. It is the best library for the data table.

Run this command to install it

npm install react-data-table-component styled-components

Then you have to import it in the react component page and use it

import DataTable from 'react-data-table-component';

const data = [{ id: 1, title: 'DataTable in ReactJS', year: '2021' } ...];
const columns = [
{
   name: 'Name',
   selector: 'name',
   sortable: true,
},
{
   name: 'Username',
   selector: 'username',
   sortable: true,
},
{
   name: 'Email',
   selector: 'email',
   sortable: true,
},
{
   name: 'Phone',
   selector: 'phone',
   sortable: true,
},
{
   name: 'Website',
   selector: 'website',
   sortable: true,
},
];

class MyComponent extends Component {
   render() {
     return (
        <datatable title="YourBlogCoach" columns="{columns}" data="{data}"> 
        </datatable>
     )
   }
};

Check here for tutorial

Upvotes: -2

tmhao2005
tmhao2005

Reputation: 17474

The problem I can see here is that you initialize the plugin table in incorrect way. In order to include DataTable plugin, you should call as require('datatables.net')(window, $). Then after you have done loading data, you just simply call sync data to table again. Here is the snippet:

const $ = require("jquery");
require("datatables.net")(window, $);

// Keep as you have done
async getUsersData() {
  const res = await axios.get("https://jsonplaceholder.typicode.com/users");
  console.log(res.data);
  this.setState({ loading: false, users: res.data });
}

// Init table data as component is mounted
componentDidMount() {
  this.getUsersData().then(() => this.syncTable());
}

// Split as new function to init the datatable
syncTable() {
  this.$el = $(this.el);
  this.$el.DataTable({
    data: this.state.users, //option 1
    // data: this.getUsersData1(), //option 2
    columns: [
      { title: "Name", data: "name" },
      { title: "Username", data: "username" },
      { title: "Email", data: "email" },
      { title: "Phone", data: "phone" },
      { title: "Website", data: "website" }
    ]
  });
}

Here is the codesandbox for you: https://codesandbox.io/s/gallant-faraday-e25mk?file=/src/App.js

Upvotes: 1

Related Questions