Displaying tabular data from Database using React Js

A table is an arrangement which organizes information into rows and columns. It is used to store and display data in a structured format.

The react-table is a lightweight, fast, fully customizable (JSX, templates, state, styles, callbacks), and extendable Datagrid built for React. It is fully controllable via optional props and callbacks.

Features

  1. It is lightweight at 11kb (and only need 2kb more for styles).
  2. It is fully customizable (JSX, templates, state, styles, callbacks).
  3. It is fully controllable via optional props and callbacks.
  4. It has client-side & Server-side pagination.
  5. It has filters.
  6. Pivoting & Aggregation
  7. Minimal design & easily themeable

Installation

Let us create a React app using the following command.

Next, we need to install react-table. We can install react-table via npm command, which is given below.

Once, we have installed react-table, we need to import the react-table into the react component. To do this, open the src/App.js file and add the following snippet.

Let us assume we have data which needs to be rendered using react-table.

Along with data, we also need to specify the column info with column attributes.

Inside the render method, we need to bind this data with react-table and then returns the react-table.

Probably every website consumes data in one way or the other. Most commonly you will come across a situation where you need to display data in a table.

In this tutorial, we will look at how to fetch and display JSON data into a table.

Let’s get started!

Project setup

Get started by creating react app on your machine or open your browser and visit react.new

A new CodeSandbox environment will open with React project setup.

Fetching Data from API

In React, there are many ways to fetch data but for this tutorial, we will be using the fetch() function to get dummy JSON data.

We will be using a dummy JSON API https://dummyjson.com/products which returns the data of random products and further we will be using this data to display it in our table.

// App.js import { useEffect } from "react"; import "./App.css"; function App() { useEffect(() => { fetch(`https://dummyjson.com/products`) .then((response) => response.json()) .then((actualData) => console.log(actualData)) .catch((err) => { console.log(err.message); }); }, []); return ( <div className="App"> <p>Hello, world!</p> </div> ); } export default App;

In this code, we’re fetching the data inside the useEffect hook so that it only loads the data on the initial render. You can learn more about how to fetch data in React here.

In this article I will explain with an example, how to fetch Data from API and display in HTML Table using ReactJS.

This article will make use of ASP.Net MVC and ReactJS.Net as backend.

 

 

The JSON string returned from the API

The following JSON string is returned from the ASPSnippets Test API.

[

   {

      "CustomerId":1,

      "Name":"John Hammond",

      "Country":"United States"

   },

   {

      "CustomerId":2,

      "Name":"Mudassar Khan",

      "Country":"India"

   },

   {

      "CustomerId":3,

      "Name":"Suzanne Mathews",

      "Country":"France"

   },

   {

      "CustomerId":4,

      "Name":"Robert Schidner",

      "Country":"Russia"

   }

]

 

 

Software Information

This article makes use of Visual Studio 2019, MVC 5 and .Net Framework 4.5.

 

 

Integrating ReactJS with ASP.Net MVC

For more information on integrating ReactJS with ASP.Net MVC, please refer my article ASP.Net MVC ReactJS Hello World Example.

 

 

Controller

The Controller consists of following Action method.

Action method for handling GET operation

Inside this Action method, simply the View is returned.

public class HomeController : Controller

{

    // GET: Home

    public ActionResult Index()

    {

        return View();

    }

}

 

 

ReactJS JSX file

Following ReactJS.jsx file consists of a CustomerTable class which extends ReactJS Component.

Constructor

Inside the Construtor, the props variable is sent to the super class so that it can be used later in the render function.

Then an Array named customers is assigned to the state.

 

Event Handlers

componentDidMount

This function is called when the React Component is loaded in the DOM.

Inside this function, a Cross Domain AJAX call is made to the external API using the Fetch API.

And inside the success event handler of the Fetch API, the received response is set in the customers Array of the state using the setState function.

 

Render function

The Render function returns an HTML Table with Header Row and dynamic rows generated using the customers array.

Inside the Render function, with the help of map function, the Table rows are dynamically generated using the customers Array.

Finally, the ReactDOM.render function, render’s the class in a HTML DIV with ID dvCustomersGrid.

class CustomerTable extends React.Component {

    constructor(props) {

        super(props);

        this.state = {

            customers: []

        }

    }

    componentDidMount() {

        fetch("https://raw.githubusercontent.com/aspsnippets/test/master/Customers.json")

        .then(res => res.json())

        .then(

            (customers) => {

                this.setState({ customers: customers });

            },

            (error) => {

                alert(error);

            }

        )

    }

 

    render() {

        return (<table cellPadding="0" cellSpacing="0">

            <thead>

                <tr>

                    <th>CustomerId</th>

                    <th>Name</th>

                    <th>Country</th>

                </tr>

            </thead>

 

            <tbody>

                {this.state.customers.map(customer =>

                    <tr>

                        <td>{customer.CustomerId}</td>

                        <td>{customer.Name}</td>

                        <td>{customer.Country}</td>

                    </tr>

                )}

            </tbody>

        </table>);

    }

}

 

ReactDOM.render(

    <CustomerTable />,

    document.getElementById('dvCustomersGrid')

);

 

 

View

The View consists of an HTML DIV dvCustomersGrid inside which the generated HTML Table from the ReactJS will be displayed.

How do you make a tabular form in react JS?

To create a table in ReactJS, we need to use a package manager (Yarn or npm) to install a react-table and then import the library into our React app by running the following command. import { useTable } from 'react-table'; After the react-table has been installed and imported, we must describe our data and columns.

How do you fetch data from local database in react JS?

There are different of fetching data:.
By using Fetch API..
By using Axios library..
By using async-await syntax..
By using custom hooks..
By using React Query..

How display JSON data in table format with React?

Step 1: Open the terminal and create react app. Step 2: Change the directory to that folder by executing the command. Project Structure: It will look like the following. Step 3: Creating a JSON Object File here and Save it as data.

How do you display data in a list in React?

Now, let us see how we create a list in React. To do this, we will use the map() function for traversing the list element, and for updates, we enclosed them between curly braces {}. Finally, we assign the array elements to listItems. Now, include this new list inside <ul> </ul> elements and render it to the DOM.