How to Add a React Pivot Table to Your Web Application
Tags: webdev, devops, javascript, tutorial
Published: 2023-08-22 14:31:42

---
canonical_url: https://developer.mescius.com/blogs/how-to-add-a-react-pivot-table-to-your-web-application
description: Learn how to add the React Pivot Table add-on from SpreadJS to your web application. See more today.
---

Pivot Tables are undeniably one of the most powerful data analysis tools; they help organize data so users can detect recurring patterns more easily. Pivot Tables help users create customized tables from large data groups. The user can summarize, sort, reorganize, group, count, total, or average data effortlessly within a table using pivot functionalities.

[**SpreadJS**, a React spreadsheet component](https://developer.mescius.com/spreadjs/react-spreadsheet-components), has a [Pivot Tables add-on](https://developer.mescius.com/spreadjs/javascript-excel-spreadsheet-pivot-table) feature that allows React developers to create Excel-like Pivot Tables programmatically in their applications or allow end-users to create them with a familiar UI easily.

![React Pivot Table](https://files.grapecity.com/gc-website-media/rceofos3/01-sjs-react-pivot-table.png?width=500&height=262.5)

[**Check out our online React Pivot Table demo to see how to get started with SpreadJS’s PivotTables**](https://developer.mescius.com/spreadjs/demos/features/pivot-table/overview/react).

This blog will go through some of the essential properties and features of the React spreadsheet Pivot Table API that will help you customize the appearance of your pivot tables and reports derived from these Pivot Tables.

*   [Create a React Pivot Table](#create)
*   [Pivot Layout](#layout)
*   [Pivot Table Theme](#theme)
*   [Pivot Styles](#styles)
*   [Pivot Table AutofitColumn](#autofitcolumn)
*   [Pivot Table Slicers](#slicers)
*   [Pivot ContextMenu](#contextmenu)
*   [Pivot Conditional Formatting](#formatting)

[**You can download a sample application here to follow along with the blog.**](https://gccontent.blob.core.windows.net/gccontent/blogs/spread/20230712-spjs-react-pivot-table-blog-sample/features_pivot-table_overview_React_blog.zip)

## <a id="create"></a>Create a React Pivot Table

Imagine having countless rows of data containing specific information. For example, in the datasheet below, we have a large number of records showing the best-selling video games.

![React Pivot Table](https://files.grapecity.com/gc-website-media/yefblo31/02-react.png?width=500&height=317.9460580912863)

The goal is to create a report summarizing this raw data into more insightful information. The below function shows how to programmatically add a pivot table and add fields in a [React application](https://developer.mescius.com/spreadjs/demos/features/pivot-table/overview/react) using [SpreadJS’s **PivotTable** class API](https://developer.mescius.com/spreadjs/api/classes/GC.Spread.Pivot.PivotTable-1).

```
     let initPivotTable = function(sheet, tableName){
            sheet.name("Basic PivotTable");
            sheet.setRowCount(250);
            let pivotTableOptions = {bandRows:true,bandColumns:true};
            let pivotTable = sheet.pivotTables.add("PivotTable", tableName, 1, 1, GC.Spread.Pivot.PivotTableLayoutType.tabular, GC.Spread.Pivot.PivotTableThemes.medium14, pivotTableOptions);
            pivotTable.suspendLayout();

            pivotTable.add("Genre", "Genre", GC.Spread.Pivot.PivotTableFieldType.rowField);
            pivotTable.add("Name", "Name", GC.Spread.Pivot.PivotTableFieldType.rowField);

            pivotTable.add("NA_Sales", "NA_Sales", GC.Spread.Pivot.PivotTableFieldType.valueField, GC.Pivot.SubtotalType.sum);
            pivotTable.add("EU_Sales", "EU_Sales", GC.Spread.Pivot.PivotTableFieldType.valueField, GC.Pivot.SubtotalType.sum);
            pivotTable.add("JP_Sales", "JP_Sales", GC.Spread.Pivot.PivotTableFieldType.valueField, GC.Pivot.SubtotalType.sum);
            pivotTable.add("Other_Sales", "Other_Sales", GC.Spread.Pivot.PivotTableFieldType.valueField, GC.Pivot.SubtotalType.sum);
            pivotTable.add("Global_Sales", "Global_Sales", GC.Spread.Pivot.PivotTableFieldType.valueField, GC.Pivot.SubtotalType.sum);

            pivotTable.resumeLayout();
        }
```

After applying this code, the PivotTable will display in the React application like so:

![React Pivot Table](https://files.grapecity.com/gc-website-media/ubklr51n/03-react.png?width=500&height=435.59718969555036)

Another way of creating a pivot table is by using the [Pivot Panel](https://developer.mescius.com/spreadjs/demos/features/pivot-table/pivot-panel/overview/react) offered by SpreadJS. To initialize the Pivot Panel, first, create a DOM element, in this case, a DIV with an ID “panel”:

```
    return (
            <div class="sample-tutorial">
                <div class="sample-spreadsheets">
                    <SpreadSheets workbookInitialized={spread=>initSpread(spread)}>
                    </SpreadSheets>
                </div>
                 <div class="sample-panel">
                    <div id="panel"></div>
                </div>
            </div>
        );
```

Apply CSS for the side panel. Interesting side note - developers can customize the styling and appearance of the Pivot Panel here through the CSS:

```
    .sample-panel {
      float: right;
      width: 300px;
      padding: 12px;
      height: 100%;
      box-sizing: border-box;
      background: #fbfbfb;
      overflow: auto;
    }

    .gc-panel {
      padding: 10px;
      background-color: rgb(230, 230, 230);
    }

    #panel {
      position: absolute;
      right: 0;
      width: 300px;
      height: 100%;
      top: 0;
    }
```

Then use [SpreadJS’s **PivotPanel** constructor](https://developer.mescius.com/spreadjs/api/classes/GC.Spread.Pivot.PivotPanel#constructor) to initialize the panel:

```
    //code to add pivot panel in the working spreadsheet.
    var panel = new GC.Spread.Pivot.PivotPanel("myPivotPanel", myPivotTable, document.getElementById("panel"));
```

The application will now display the SpreadJS React PivotTable with the side panel allowing end-users to drag and drop needed fields according to the report logic.

![React Pivot Table](https://files.grapecity.com/gc-website-media/3q3fmgp3/04-pivottable-pivot-panel.gif?width=500&height=281.25)

## <a id="layout"></a>Pivot Layout

SpreadJS allows you to choose from [three different pivot table layouts](https://developer.mescius.com/spreadjs/demos/features/pivot-table/pivot-layout/react) to offer different visualizations of your data. This includes the Compact, Outline, and Tabular form layouts. By default, the pivot table layout is Compact form. Still, users can set the layout when creating the pivot table using the [**PivotTable** constructor](https://developer.mescius.com/spreadjs/api/classes/GC.Spread.Pivot.PivotTable-1#constructor)or change the layout using the [**layoutType** function](https://developer.mescius.com/spreadjs/api/classes/GC.Spread.Pivot.PivotTable-1#layouttype). The function has an integer argument corresponding to the form layout (0 - compact, 1 - outline, 2 - tabular).

```
    // Set an outline form (1)
    pivotTable.layoutType(1);
```

### Compact Form (0)

This layout contains all the Row fields in one column in a hierarchical structure.

This layout form optimizes readability by keeping related data in one column. Still, if you copy and paste the data into a new worksheet, it will be harder to do further analysis.

![React Pivot Table](https://files.grapecity.com/gc-website-media/xhiogkdx/05-react.png?width=500&height=217.44324970131424)

### Outline Form (1)

This layout has a hierarchical structure, but each Row field is in a separate column in the pivot table. It displays one column per field and provides space for field headers.

Using this form, you can include Field headers in each column, repeat all item labels and reuse the data of the Pivot Table in a new location for further analysis. Still, this form uses horizontal space, so it might not be beneficial to use it in some cases.

![React Pivot Table](https://files.grapecity.com/gc-website-media/mqph1aoz/06-react.png?width=500&height=244.9528936742934)

### Tabular Form (2)

This layout is a hierarchical structure, and each Row field is in a separate column in the pivot table. It can display subtotals at the top of every group because items in the next column are displayed in one row below the current item.

This traditional table format is very preceptive for the users. It includes Field headers in each column and allows you to have all the item labels repeated and reuse the Pivot Table data in a new location for further analysis. As a disadvantage, this layout uses horizontal space, and subtotals can’t appear at the top of the group if you want to have those at the top.

![React Pivot Table](https://files.grapecity.com/gc-website-media/ch1ivfh1/07-react.png?width=500&height=203.08310991957106)

## <a id="theme"></a>Pivot Table Theme

SpreadJS’s React PivotTable provides 85 predefined themes - 29 light, 28 medium, and 28 dark.

You can apply the pivot table theme when [adding the pivot table](https://developer.mescius.com/spreadjs/api/classes/GC.Spread.Pivot.PivotTable-1#add), or you can use the [**theme** function](https://developer.mescius.com/spreadjs/api/classes/GC.Spread.Pivot.PivotTable-1#theme).

```
    let pivotTable = sheet.pivotTables.add("PivotTable", table.name(), 0, 0, GC.Spread.Pivot.PivotTableLayoutType.outline, GC.Spread.Pivot.PivotTableThemes.medium2);
    //pivotTable.theme(GC.Spread.Pivot.PivotTableThemes.dark2);
    //pivotTable.theme("dark2");
```

Choosing the right theme improves the appearance of your pivot table and offers a more professional presentation of data for the end receivers of your report. [Check out SpreadJS’s online demo here to see for yourself](https://developer.mescius.com/spreadjs/demos/features/pivot-table/pivot-customize/pivot-theme/react).

![React Pivot Tables](https://files.grapecity.com/gc-website-media/ciohblu0/08-pivottable-panel-themes.gif?width=500&height=260.42402826855124)

## <a id="styles"></a>Pivot Styles

You can apply a [pivot table style](https://developer.mescius.com/spreadjs/docs/features/pivot-table/themes-and-style#style) to highlight any specific data. The [**style** method](https://developer.mescius.com/spreadjs/api/classes/GC.Spread.Pivot.PivotTable-1#setStyle) can apply styles to row, column, value, and label fields. For example, the following code snippet applies a style to the value fields.

```
    // Get the pivot area
    let labelPivotArea = {
        dataOnly: true,
        references: [{
          fieldName: "Values",
          items: ["Global_Sales", "NA_Sales"]
        }]
    };

    // Create style
    let style = new GC.Spread.Sheets.Style();
    style.backColor = "#82bc00";

    // Set pivot style
    pivotTable.setStyle(labelPivotArea, style);
```

This code will highlight the value fields “Global_Sales”, “JP_Sales”, and “NA_Sales”:

![React Pivot Tables](https://files.grapecity.com/gc-website-media/flgfttv2/09-react.png?width=500&height=492.7916120576671)

With this support, React developers can customize and apply their own rules, styles, and formatting to certain pivot table fields; check out [SpreadJS’s online Pivot Style demo](https://developer.mescius.com/spreadjs/demos/features/pivot-table/pivot-style/react) for more information.

## <a id="autofitcolumn"></a>Pivot Table AutofitColumn

SpreadJS’s React pivot table offers an [**AutofitColumn** function](https://developer.mescius.com/spreadjs/api/classes/GC.Spread.Pivot.PivotTable-1#autofitcolumn) that adjusts the pivot table's column width to accommodate the longest value in a field. Overall, it is a helpful function and convenient when working with long, text-based fields.

```
    // Auto fit Pivot Table columns
    pivotTable.autoFitColumn();
```

The GIF below demonstrates this function; when the page reloads, the **autoFitColumn** function is invoked:

![React Pivot Tables](https://files.grapecity.com/gc-website-media/23ahn343/10-pivottable-panel-autofit.gif?width=500&height=262.54416961130744)

## <a id="slicers"></a>Pivot Table Slicers

Pivot Table Slicers are an interactive visual control that allows users to filter and manipulate data within a pivot table. They provide a user-friendly way to narrow down the data displayed in a pivot table by selecting specific criteria, such as dates, categories, or other relevant dimensions. Using slicers, users can quickly analyze and explore data subsets without modifying the underlying pivot table structure. SpreadJS supports both the [Item Slicer](https://developer.mescius.com/spreadjs/docs/features/pivot-table/pt-slicer/pivot-table-item-slicer) and [Timeline Slicer](https://developer.mescius.com/spreadjs/docs/features/pivot-table/pt-slicer/pivot-table-timeline-slicer).

<div class="pm-table-container with-shadow-observer" data-layout="default">

<div class="pm-table-wrapper">

<table border="0" data-number-column="false">

<tbody>

<tr>

<th class="ak-renderer-tableHeader-sortable-column__wrapper" colspan="1" rowspan="1" data-colwidth="122" aria-sort="none">

<div class="ak-renderer-tableHeader-sortable-column">

PivotTable Item Slicer

</div>

</th>

<th class="ak-renderer-tableHeader-sortable-column__wrapper" colspan="1" rowspan="1" data-colwidth="168" aria-sort="none">

<div class="ak-renderer-tableHeader-sortable-column">

PivotTable Timeline Slicer

</div>

</th>

</tr>

<tr>

<td colspan="1" rowspan="1" data-colwidth="122">

[![React Pivot Table - Item Slicers](https://files.grapecity.com/gc-website-media/l5fabbfb/untitled-design-26.png?width=500&height=358.1730769230769)](https://developer.mescius.com/spreadjs/demos/features/pivot-table/pivot-slicer/pivot-table-item-slicer/react)

</td>

<td colspan="1" rowspan="1" data-colwidth="168">

[![React Pivot Table - Timeline slicers](https://files.grapecity.com/gc-website-media/z1ad2kom/12-react.png?width=419&height=300&mode=max)](https://developer.mescius.com/spreadjs/demos/features/pivot-table/pivot-slicer/pivot-table-timeline-slicer/react)

</td>

</tr>

</tbody>

</table>

</div>

</div>

Check out [SpreadJS’s React Slicer demo](https://developer.mescius.com/spreadjs/demos/features/pivot-table/pivot-slicer/pivot-slicer-overview/react) to try the slicers for yourself.

## <a id="contextmenu"></a>Pivot ContextMenu

SpreadJS offers a [Pivot ContextMenu](https://developer.mescius.com/spreadjs/demos/features/pivot-table/pivot-context-menu/react) that empowers users to perform various actions on pivot tables effortlessly. This feature allows users to sort data, rearrange field headers, and personalize the control by expanding or collapsing field values. The Pivot ContextMenu provides a user-friendly and compact interface to modify the appearance of pivot table data.

When interacting with different parts of a pivot table and then right-clicking, [SpreadJS presents distinct context menu options](https://developer.mescius.com/spreadjs/docs/features/pivot-table/context-menu). Here are some of the React Pivot Table Context Menus:

<div class="pm-table-container with-shadow-observer" data-layout="default">

<div class="pm-table-wrapper">

<table border="0" data-number-column="false">

<tbody>

<tr>

<th class="ak-renderer-tableHeader-sortable-column__wrapper" colspan="1" rowspan="1" data-colwidth="122" aria-sort="none">

<div class="ak-renderer-tableHeader-sortable-column">

The page area

</div>

</th>

<th class="ak-renderer-tableHeader-sortable-column__wrapper" colspan="1" rowspan="1" data-colwidth="168" aria-sort="none">

<div class="ak-renderer-tableHeader-sortable-column">

The header area

</div>

</th>

</tr>

<tr>

<td colspan="1" rowspan="1" data-colwidth="122">

![React Pivot Table](https://files.grapecity.com/gc-website-media/pegd5pte/13-pt-page-area-cm.png?width=500&height=332.03559510567294)

</td>

<td colspan="1" rowspan="1" data-colwidth="168">

![React Pivot Table](https://files.grapecity.com/gc-website-media/ugtcwshu/14-pt-header-area-cm.png?width=500&height=332.03559510567294)

</td>

</tr>

<tr>

<th class="ak-renderer-tableHeader-sortable-column__wrapper" colspan="1" rowspan="1" data-colwidth="122" aria-sort="none">

<div class="ak-renderer-tableHeader-sortable-column">

The data area

</div>

</th>

<th class="ak-renderer-tableHeader-sortable-column__wrapper" colspan="1" rowspan="1" data-colwidth="168" aria-sort="none">

<div class="ak-renderer-tableHeader-sortable-column">

The Grand Total area

</div>

</th>

</tr>

<tr>

<td colspan="1" rowspan="1" data-colwidth="168">

![React Pivot Table](https://files.grapecity.com/gc-website-media/5wsftvj4/15-pt-data-area-cm.png?width=500&height=332.03559510567294)

</td>

<td colspan="1" rowspan="1" data-colwidth="168">

![React Pivot Table](https://files.grapecity.com/gc-website-media/krjkktj5/16-pt-grand-total-area-cm.png?width=500&height=332.03559510567294)

</td>

</tr>

</tbody>

</table>

</div>

</div>

[Users can also format values with given formats or customized ones](https://developer.mescius.com/spreadjs/docs/features/pivot-table/context-menu#custom-format-in-value-fields) by choosing the “**Value Field Settings...**" option from the data area or the Grand Total area context menu to open the dialog window.

![React Pivot Table](https://files.grapecity.com/gc-website-media/jfcna0sz/17-pivottable-value-field-settings.gif?width=500&height=281.25)

## <a id="formatting"></a>Pivot Conditional Formatting

Conditional Formatting is a powerful tool that allows you to quickly highlight data fields, making it easier to identify outliers or refine your results. In a pivot area, you have the flexibility to apply, retrieve, and remove conditional formatting rules. These rules remain in effect even if you make changes to the PivotTable layout.

You can apply Conditional Formatting to the SpreadJS’s React Pivot Table using the [**addConditionalRule** method](https://developer.mescius.com/spreadjs/api/classes/GC.Spread.Pivot.PivotTable-1#addconditionalrule).

Check out [SpreadJS’s online React demo](https://developer.mescius.com/spreadjs/demos/features/pivot-table/pivot-conditional-rules/react). This demo applies different color formatting depending on the cell values, with green being the lowest and red the highest.

[![React Pivot Table](https://files.grapecity.com/gc-website-media/a5yogyvs/18-react.png?width=500&height=282.5365205843293)](https://developer.mescius.com/spreadjs/demos/features/pivot-table/pivot-conditional-rules/react)

We hope you enjoyed learning how to create and customize React Spreadsheet Pivot Tables. [You can download the sample application from the blog here](https://gccontent.blob.core.windows.net/gccontent/blogs/spread/20230712-spjs-react-pivot-table-blog-sample/features_pivot-table_overview_React_blog.zip). This article only scratches the surface of the full capabilities of [**SpreadJS**](https://developer.mescius.com/spreadjs/react-spreadsheet-components), the React spreadsheet component.

Review the [documentation](https://developer.mescius.com/spreadjs/docs/overview) to see some of the many available features, and check out our [online demos](https://developer.mescius.com/spreadjs/demos/) to see the features in action and interact with the sample code. Integrating a spreadsheet component into your React applications allows you to customize your users' experience and provide them with familiar spreadsheet functionality.

To learn more about SpreadJS and the new features added to the v16 release, check out our [release blog](https://developer.mescius.com/blogs/spreadjs-v-16-service-pack-1-released).