React Datatables is a powerful library for creating dynamic data tables. It allows developers to easily create tables with dynamic data from a variety of sources, including JSON, CSV, and HTML. It also provides features such as sorting, filtering, and pagination.
In this example, we will create a React Datatable component that displays a list of users from a JSON file. We will use the React Hooks API to fetch the data and display it in the table. We will also add sorting, filtering, and pagination features to the table.
First, we will create a React component that will fetch the data from the JSON file. We will use the useEffect hook to fetch the data when the component mounts.
import React, { useEffect, useState } from ‘react’;
const UserTable = () => {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch(‘/data.json’)
.then(res => res.json())
.then(data => setUsers(data));
}, []);
return (
User Table
Name | Age | |
---|---|---|
{user.name} | {user.email} | {user.age} |
);
};
export default UserTable;
Next, we will use the React Datatables library to create the table. We will pass the users array as the data prop and add sorting, filtering, and pagination features.
import React, { useEffect, useState } from ‘react’;
import { useTable } from ‘react-datatables-hook’;
const UserTable = () => {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch(‘/data.json’)
.then(res => res.json())
.then(data => setUsers(data));
}, []);
const columns = [
{
name: ‘Name’,
selector: ‘name’,
sortable: true,
},
{
name: ‘Email’,
selector: ’email’,
sortable: true,
},
{
name: ‘Age’,
selector: ‘age’,
sortable: true,
},
];
const { dataTable } = useTable({
columns,
data: users,
pagination: true,
sorting: true,
filtering: true,
});
return (
User Table
{dataTable}
);
};
export default UserTable;
Finally, we will add some styling to the table using CSS.
table {
width: 100%;
border-collapse: collapse;
}
th,
td {
padding: 8px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background-color: #f2f2f2;
}
tr:hover {
background-color: #f5f5f5;
}
React is one of the most popular front-end libraries for building web applications. When building web applications, you often need to display data in tables, and that’s where DataTables come in. DataTables are a powerful tool for displaying and manipulating large sets of data in a tabular format. In this tutorial, you will learn how to integrate dataTables and display dynamic data in react application using jQuery, datatable, bootstrap and axios plugin.
If you want to integrate DataTable in your react app. Want to show any list using end datable. So in this tutorial, you will learn how to integrate a DataTable and show a list with the help of a DataTable.
How to Display Data in to DataTable In React Js
Use the following steps to create simple list and display dynamic data from server in react js app; as shown below:
- Step 1 – Create New React App
- Step 2 – Install React-Select and Bootstrap
- Step 3 – Install jQuey and DataTable Library
- Step 4 – Create List Component
- Step 5 – Add Component in App.js
- Step 6 – Create getList.php File
Step 1 – Create New React App
In this step, open your terminal and execute the following command on your terminal to create a new react app:
npx create-react-app my-react-app
To run the React app, execute the following command on your terminal:
npm start
Check out your React app on this URL: localhost:3000
Step 2 – Install Axios and Bootstrap
In this step, execute the following command on terminal install Axios and bootstrap libraries into your react app:
npm install bootstrap --save npm install axios --save
Add bootstrap.min.css file in src/App.js
file:
import React, { Component } from 'react'
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
function App() {
return (
<div>
<h2>React js Datatables with Dynamic Data Example</h2>
</div>
);
}
export default App;
Step 3 – Install jQuey and DataTable Library
In this step, execute the following command on terminal to jQuey and DataTable libraries into your react app:
npm install --save datatables.net-dt npm install jquery --save
Step 4 – Create List Component
Once you have installed the required packages, the next step is to create a basic table. Then you will use the ListComponent.js DataTable
component from the react-data-table-component
package to create our table. Here’s an code:
import React from 'react';
import './App.css';
//jQuery libraries
import 'jquery/dist/jquery.min.js';
//Datatable Modules
import "datatables.net-dt/js/dataTables.dataTables"
import "datatables.net-dt/css/jquery.dataTables.min.css"
import $ from 'jquery';
//For API Requests
import axios from 'axios';
class ListComponent extends Component {
// State array variable to save and show data
constructor(props) {
super(props)
this.state = {
data: [],
}}
componentDidMount() {
//Get all users details in bootstrap table
axios.get('http://localhost/getList.php').then(res =>
{
//Storing users detail in state array object
this.setState({data: res.data});
});
//initialize datatable
$(document).ready(function () {
setTimeout(function(){
$('#example').DataTable();
} ,1000);
});
}
render(){
//Datatable HTML
return (
<div className="MainDiv">
<div class="jumbotron text-center">
<h3>LaraTutorials.com</h3>
</div>
<div className="container">
<table id="example" class="table table-hover table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Email</th>
<th>Username</th>
</tr>
</thead>
<tbody>
{this.state.data.map((result) => {
return (
<tr>
<td>{result.id}</td>
<td>{result.email}</td>
<td>{result.username}</td>
</tr>
)
})}
</tbody>
</table>
</div>
</div>
);
}
}
export default ListComponent;
This is a JavaScript code that is using React library to create a component called ListComponent
. The component is rendering a HTML table using the datatables.net
library to display a list of users fetched from an API endpoint.
Here is a breakdown of the code:
- The code is importing the React library and the
App.css
file, which contains the styling for the component. - The code is also importing the jQuery library,
datatables.net
modules, and the Axios library for making HTTP requests. - The
ListComponent
class is defined, which extends theComponent
class from the React library. The constructor method is used to initialize the state of the component, which includes an empty array to store the data fetched from the API. - The
componentDidMount
method is called after the component has mounted and is used to make an API request to fetch the list of users. Once the response is received, thedata
state array is updated with the fetched data. - The
render
method is called to render the HTML table with the list of users. Themap
method is used to loop through thedata
state array and render a row for each user in the table. Thedatatables.net
library is used to apply styling and functionality to the table. - The
ListComponent
is exported as the default export of the module, making it available for use in other parts of the application.
Overall, this code is a basic implementation of a React component that fetches and displays data from an API using the datatables.net
library.
Step 5 – Add Component in App.js
In this step, you need to add the ListComponent.js file in src/App.js
file:
import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import ListComponent from './ListComponent'
function App() {
return (
<div className="App">
<ListComponent/>
</div>
);
}
export default App;
Step 6 – Create getList.php File
In this step, create a new file getList.php and add the following code into it:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "demo";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Getting data query
$trp = mysqli_query($conn, "SELECT * from users");
$rows = array();
while($r = mysqli_fetch_assoc($trp)) {
$rows[] = $r;
}
print json_encode($rows);
?>
This is a PHP code that connects to a MySQL database, retrieves data from a table named “users”, and outputs it in JSON format.
Here’s what the code does step by step:
- The variables
$servername
,$username
,$password
, and$dbname
are set to the values required to connect to the MySQL database. These variables will be used later when creating a new mysqli connection. - A new mysqli connection is created using the
mysqli()
constructor. This connection uses the parameters$servername
,$username
,$password
, and$dbname
. - The code checks if the connection was successful by calling
$conn->connect_error
and if the connection fails, it will output the error message using thedie()
function. - A SQL query is executed to retrieve data from the “users” table using
mysqli_query()
, which takes two parameters: the mysqli connection and the SQL query. The retrieved data is stored in$trp
. - An empty array
$rows
is initialized, and a while loop is used to loop through each row of data in$trp
usingmysqli_fetch_assoc()
. Each row of data is added to the$rows
array using the[]
syntax. - Finally,
json_encode()
function is used to convert the$rows
array to a JSON string andprint()
function is used to output the JSON string.
The resulting output will be a JSON encoded array containing all the data from the “users” table.
Conclusion
React js datatable example; In this tutorial, you have learned how to integrate dataTables and display dynamic data in react application using jQuery, datatable, bootstrap and axios plugin.