1. Code
  2. JavaScript
  3. React

Working With Tables in React: Part One

Scroll to top
This post is part of a series called Working With Tables in React.
Working With Tables in React: Part Two

One of the most common user interface elements for presenting your data is a table. It turns out that there are many aspects to control when working with tables, such as:

  • defining columns and headers
  • various cell formats (text, numbers, check boxes)
  • resizing
  • filtering
  • dynamic growing
  • styling

In this two-part series, you will learn about the ins and outs of working with tabular data in React using the React Bootstrap Table component. You'll be able to create sophisticated and professional-looking tables with little effort and yet be able to customize every aspect.

Getting Started  

 

To start, you should be familiar with React itself. If you need a primer on React, Envato Tuts+ has a great series to help you get started with React. In this tutorial, we'll focus on working with React Bootstrap Table2.

To start, create a React app with the create-react-app command. You can learn how to set create-react-app up in React Crash Course for Beginners.

1
create-react-app react-table-app

Now navigate to the project folder and install React Bootstrap Table 2 and Bootstrap.

1
cd react-table-app
2
npm install react-bootstrap-table-next --save
3
npm install --save bootstrap@4.0.0

Create a Basic Table

We will start with a basic table. We first import the BootstrapTable component and CSS as shown below.

1
import logo from './logo.svg';
2
import './App.css';
3
import React, { Component } from 'react';
4
import '../node_modules/bootstrap/dist/css/bootstrap.min.css'; 
5
import BootstrapTable from 'react-bootstrap-table-next';
6
 

First, we initialize the data and column variables, and then we assign the data to the BootstrapTable component. The data contains the names of some characters from the hilarious show Arrested Development

1
const data = [
2
  {id: 1, name: 'Gob', value: '2'},
3
  {id: 2, name: 'Buster', value: '5'},
4
  {id: 3, name: 'George Michael', value: '4'}
5
];
6
const columns = [{
7
  dataField: 'id',
8
  text: 'Product ID'
9
}, {
10
  dataField: 'name',
11
  text: 'Product Name'
12
}, {
13
  dataField: 'value',
14
  text: 'Product value'
15
}]; 

The Bootstrap component takes in the following attributes.

  • keyField
  • data
  • columns

The render() method renders a table with three columns: "ID", "Name", and "Value".

1
class App extends Component {
2
  render() {
3
    return (
4
      <div className="App">
5
        <p className="Table-header">Basic Table</p>

6
        
7
        <BootstrapTable keyField='id' data={ person } columns={ columns } />

8
      </div>

9
    );
10
  }
11
}

To view the table, issue the command npm start--reload. The configuration created by create-react-app watches over your code and recompiles whenever you change anything, so you only need to run it once. Then, every change will automatically be reflected.

1
Compiled successfully!
2
3
You can now view my-table-app in the browser.
4
5
  Local:            https://localhost:3002
6
  On Your Network:  http://192.168.43.206:3002
7
8
Note that the development build is not optimized.
9
To create a production build, use npm run build.
10

Here is the result:

basic tablebasic tablebasic table

Note that each column has the same width.

Working With Columns

You can control many aspects of the columns. In particular, the column widths can be specified in absolute units, as percentages, or left unspecified. The column width of unspecified columns is the remainder divided equally. For example, for our basic table, let's specify the columns as follows:

  • first column: 20%
  • second column: 60%
  • third column: 20%

You can also manage the alignment of text and columns as well as the style of headers and columns. Here is an example of how to specify different column widths, text alignment, and custom styles:

1
const columns = [{
2
  dataField: 'id',
3
  text: 'Product ID',
4
  headerStyle: (colum, colIndex) => {
5
          return { width: '20%', textAlign: 'center' };
6
        }
7
}, {
8
  dataField: 'name',
9
  text: 'Product Name',
10
  sort: true,
11
  headerStyle: (colum, colIndex) => {
12
          return { width: '60%', textAlign: 'center' };
13
        }
14
}, {
15
  dataField: 'value',
16
  text: 'Product value',
17
  headerStyle: (colum, colIndex) => {
18
          return { width: '20%', textAlign: 'center' };
19
        }
20
  
21
}]; 

The table now looks like this:

column sizingcolumn sizingcolumn sizing

Styling Your Table

You saw how to style individual columns and headers, but styling can go much further. React Bootstrap Table 2 provides a lot of options for customization. First, you can simply add the striped and hover attributes to the BootstrapTable component to get alternate background colors on each row.

Let's apply the striped and hover properties to our table.

1
class App extends Component {
2
  render() {
3
    return (
4
      <div className="App">
5
        <p className="Table-header">Basic Table</p>

6
        
7
        <BootstrapTable 
8
        striped
9
        hover
10
        keyField='id' 
11
        keyField='id'
12
        data={ person }
13
        columns={ columns } 
14
        />

15
      </div>

16
    );
17
  }
18
}
striped tablestriped tablestriped table

Check out how you would style different columns with different colors.

1
const columns = [{
2
  dataField: 'id',
3
  text: 'Product ID',
4
  style: { backgroundColor: #00afb9 }
5
}, {
6
  dataField: 'name',
7
  text: 'Product Name',
8
  style: { backgroundColor: #fdfcdc }
9
}, {
10
  dataField: 'value',
11
  text: 'Product value',
12
  style: { backgroundColor: #fed9b7 }
13
}]; 
colored columnscolored columnscolored columns

Table Sort

React Bootstrap Table 2 allows sortable columns. This is done by giving an attribute  of sort: true in the columns definition.

1
const columns = [{
2
  dataField: 'id',
3
  text: 'Product ID',
4
  style: { backgroundColor: #00afb9 }
5
}, {
6
  dataField: 'name',
7
  text: 'Product Name',
8
  style: { backgroundColor: #fdfcdc },
9
  sort: true
10
}, {
11
  dataField: 'value',
12
  text: 'Product value',
13
      style: { backgroundColor: #fed9b7 }
14
}]; 

Selecting Rows

Once you have your data in a table, you may want to select some rows to perform some operations on them. React Bootstrap Table 2 provides a wide variety of selection options. All the options are organized in a single object you pass to the component as the selectRow attribute. Here are some of the selection options:

  • single selection mode (radio button)
  • multi-selection mode (checkbox)
  • configurable column selection width
  • select on row click: by default, you must click the selector (radio button or checkbox)
  • hide selection column (useful if select on row click is true)
  • change background color on selection
  • initial selected rows
  • selection hooks (on single row or when all rows are selected).

The following components demonstrate many of these options:

edit the tableedit the tableedit the table

Other Libraries for Data Tables in React

Let's explore some other open-source React table libraries.

react-virtualized

react-virtualized is perfect for displaying a large amount of data efficiently when rendering large lists and tabular data.

react-virtualized uses a technique called virtual rendering to display extensive data efficiently. Virtual rendering only renders what is visible. For example, if you have a large list that contains a thousand items, react-virtualized will only show a fraction of the data (ones that fit on the screen) at any given moment, until the user scrolls to show more. Other features include:

  • supports rendering of grids, lists, tables, masonry, and collections
  • ability to auto-resize components
  • ability to display items in reverse order
  • ability to customize CSS classes and styles

react-table

react-table is a lightweight, open-source library that allows for fast and extendable data grids for React. It also supports hooks. Some of its best features include:

  • highly customizable 
  • supports sorting, filters, row selection, column ordering, and row expansion
  • fully controllable API
  • animatable and virtualizable
  • resizable

React Data Grid

React Data Grid is another open-source library that uses Bootstrap and is perfect for editing tables. It also has a stunning UI. Features include:

  • column sorting, searching, filtering, and grouping
  • ability to edit columns
  • expand columns to show more data

Conclusion

In this tutorial, we created a simple React application using create-react-app, added react-bootstrap-table2, populated a table with data, worked with columns, styled the table, and selected rows. 

In the next part, we'll continue the journey by expanding rows, adding rows, deleting rows, and covering pagination, cell editing, and advanced customization. Stay tuned. 

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.