Convert Figma logo to code with AI

plotly logoreact-pivottable

React-based drag'n'drop pivot table with Plotly.js charts

1,015
263
1,015
104

Top Related Projects

Open-source Javascript Pivot Table (aka Pivot Grid, Pivot Chart, Cross-Tab) implementation with drag'n'drop.

13,037

The best JavaScript Data Table for building Enterprise Applications. Supports React / Angular / Vue / Plain JavaScript.

JavaScript data grid with a spreadsheet look & feel. Works with React, Angular, and Vue. Supported by the Handsontable team ⚡

Quick Overview

The react-pivottable project is a React component that provides a highly customizable and interactive pivot table functionality. It allows users to easily analyze and visualize data by enabling them to pivot, filter, and aggregate data in a flexible manner.

Pros

  • Customizable: The project offers a wide range of customization options, allowing users to tailor the pivot table to their specific needs.
  • Interactive: The pivot table provides interactive features, such as the ability to drag and drop dimensions, filters, and aggregations, making data exploration and analysis more intuitive.
  • Flexible Data Sources: The component supports various data sources, including CSV, JSON, and SQL databases, making it versatile for different use cases.
  • Extensive Documentation: The project has comprehensive documentation, which includes detailed examples and guides, making it easier for developers to get started and integrate the component into their applications.

Cons

  • Learning Curve: The project's extensive customization options and features may have a steeper learning curve for some users, especially those new to pivot table functionality.
  • Performance: Depending on the size and complexity of the data being analyzed, the pivot table may experience performance issues, especially when dealing with large datasets.
  • Limited Visualization Options: While the project provides basic visualization capabilities, it may lack advanced charting and visualization features compared to dedicated data visualization libraries.
  • Dependency on React: The react-pivottable project is tightly coupled with the React ecosystem, which may limit its usage for developers working with other JavaScript frameworks or libraries.

Code Examples

Here are a few code examples demonstrating the usage of the react-pivottable component:

import React from 'react';
import PivotTableUI from 'react-pivottable/PivotTableUI';
import 'react-pivottable/pivottable.css';

const data = [
  { name: 'John', age: 30, gender: 'Male', city: 'New York' },
  { name: 'Jane', age: 25, gender: 'Female', city: 'Los Angeles' },
  { name: 'Bob', age: 35, gender: 'Male', city: 'Chicago' },
  { name: 'Alice', age: 28, gender: 'Female', city: 'San Francisco' },
];

const MyPivotTable = () => {
  return (
    <PivotTableUI
      data={data}
      rows={['gender']}
      cols={['city']}
      aggregatorName="Count"
      valueFilter={{ gender: ['Male'] }}
    />
  );
};

export default MyPivotTable;

This example demonstrates the basic usage of the PivotTableUI component, where we provide the data, define the rows and columns, and specify the aggregator function.

import React from 'react';
import PivotTableUI from 'react-pivottable/PivotTableUI';
import 'react-pivottable/pivottable.css';
import Plot from 'react-plotly.js';

const data = [
  { name: 'John', age: 30, gender: 'Male', city: 'New York', sales: 1000 },
  { name: 'Jane', age: 25, gender: 'Female', city: 'Los Angeles', sales: 800 },
  { name: 'Bob', age: 35, gender: 'Male', city: 'Chicago', sales: 900 },
  { name: 'Alice', age: 28, gender: 'Female', city: 'San Francisco', sales: 750 },
];

const MyPivotTableWithPlot = () => {
  return (
    <PivotTableUI
      data={data}
      rows={['gender']}
      cols={['city']}
      aggregatorName="Sum"
      vals={['sales']}
      rendererName="Plot"
      Plot={Plot}
    />
  );
};

export default MyPivotTableWithPlot;

This example demonstrates how to integrate the PivotTableUI component with the react-plotly.js library to create a pivot table with a visualization.

Getting Started

To get started with

Competitor Comparisons

Open-source Javascript Pivot Table (aka Pivot Grid, Pivot Chart, Cross-Tab) implementation with drag'n'drop.

Pros of pivottable

  • Vanilla JavaScript implementation, no React dependency
  • Longer development history and more mature codebase
  • Supports more rendering options out of the box (charts, maps)

Cons of pivottable

  • Less integration with modern React ecosystems
  • May require more setup for use in React applications
  • Fewer recent updates and potentially less active maintenance

Code Comparison

pivottable:

$("#output").pivotUI(data, {
    rows: ["Name", "Gender"],
    cols: ["Year"],
    vals: ["Births"],
    aggregatorName: "Sum",
    rendererName: "Heatmap"
});

react-pivottable:

<PivotTableUI
    data={data}
    onChange={s => this.setState(s)}
    {...this.state}
/>

Summary

pivottable is a more established library with broader rendering options and no React dependency. It's suitable for vanilla JavaScript projects but may require additional setup for React integration. react-pivottable, on the other hand, is designed specifically for React applications, offering easier integration but with potentially fewer built-in features. The choice between the two depends on the specific project requirements and the development ecosystem in use.

13,037

The best JavaScript Data Table for building Enterprise Applications. Supports React / Angular / Vue / Plain JavaScript.

Pros of ag-grid

  • More feature-rich with advanced functionality like filtering, sorting, and cell editing
  • Better performance for handling large datasets
  • Extensive documentation and community support

Cons of ag-grid

  • Steeper learning curve due to its complexity
  • Requires a commercial license for some advanced features
  • Larger bundle size compared to react-pivottable

Code Comparison

react-pivottable:

import PivotTable from 'react-pivottable/PivotTable';

<PivotTable
  data={data}
  rows={['attribute']}
  cols={['category']}
  vals={['amount']}
/>

ag-grid:

import { AgGridReact } from 'ag-grid-react';

<AgGridReact
  columnDefs={columnDefs}
  rowData={rowData}
  defaultColDef={defaultColDef}
  onGridReady={onGridReady}
/>

Summary

ag-grid offers more advanced features and better performance for large datasets, making it suitable for complex data grid requirements. However, it comes with a steeper learning curve and potential licensing costs. react-pivottable is simpler to use and implement but may lack some advanced features and performance optimizations for larger datasets. The choice between the two depends on the specific project requirements, dataset size, and desired level of customization.

JavaScript data grid with a spreadsheet look & feel. Works with React, Angular, and Vue. Supported by the Handsontable team ⚡

Pros of Handsontable

  • More feature-rich and versatile, supporting various data types and cell formats
  • Better performance with large datasets due to virtual rendering
  • Extensive API and customization options

Cons of Handsontable

  • Steeper learning curve due to its complexity
  • Larger file size, which may impact load times
  • Commercial license required for some features

Code Comparison

Handsontable:

const hot = new Handsontable(container, {
  data: dataset,
  colHeaders: true,
  rowHeaders: true,
  filters: true,
  dropdownMenu: true
});

React-pivottable:

<PivotTable
  data={dataset}
  rows={["Category"]}
  cols={["Year"]}
  vals={["Amount"]}
  aggregatorName="Sum"
/>

Key Differences

  • Handsontable is a full-featured spreadsheet-like component, while React-pivottable focuses specifically on pivot tables
  • React-pivottable is React-specific, whereas Handsontable supports multiple frameworks
  • Handsontable offers more advanced features like cell merging and custom editors, which are not available in React-pivottable
  • React-pivottable provides a simpler API for creating pivot tables, making it easier to use for specific pivot table needs

Both libraries have their strengths, and the choice between them depends on the specific requirements of your project, such as the need for advanced features, performance considerations, and the desired level of customization.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

react-pivottable

react-pivottable is a React-based pivot table library with drag'n'drop functionality. It is a React port of the jQuery-based PivotTable.js by the same author.

react-pivottable is part of Plotly's React Component Suite for building data visualization Web apps and products.

What does it do & where is the demo?

react-pivottable's function is to enable data exploration and analysis by summarizing a data set into table or Plotly.js chart with a true 2-d drag'n'drop UI, very similar to the one found in older versions of Microsoft Excel.

A live demo can be found here.

screencap

How can I use it in my project?

Drag'n'drop UI with Table output only

Installation is via NPM and has a peer dependency on React:

npm install --save react-pivottable react react-dom

Basic usage is as follows. Note that PivotTableUI is a "dumb component" that maintains essentially no state of its own.

import React from 'react';
import ReactDOM from 'react-dom';
import PivotTableUI from 'react-pivottable/PivotTableUI';
import 'react-pivottable/pivottable.css';

// see documentation for supported input formats
const data = [['attribute', 'attribute2'], ['value1', 'value2']];

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = props;
    }

    render() {
        return (
            <PivotTableUI
                data={data}
                onChange={s => this.setState(s)}
                {...this.state}
            />
        );
    }
}

ReactDOM.render(<App />, document.body);

Drag'n'drop UI with Plotly charts as well as Table output

The Plotly react-plotly.js component can be passed in via dependency injection. It has a peer dependency on plotly.js.

Important: If you build your project using webpack, you'll have to follow these instructions in order to successfully bundle plotly.js. See below for how to avoid having to bundle plotly.js.

npm install --save react-pivottable react-plotly.js plotly.js react react-dom

To add the Plotly renderers to your app, you can use the following pattern:

import React from 'react';
import PivotTableUI from 'react-pivottable/PivotTableUI';
import 'react-pivottable/pivottable.css';
import TableRenderers from 'react-pivottable/TableRenderers';
import Plot from 'react-plotly.js';
import createPlotlyRenderers from 'react-pivottable/PlotlyRenderers';

// create Plotly renderers via dependency injection
const PlotlyRenderers = createPlotlyRenderers(Plot);

// see documentation for supported input formats
const data = [['attribute', 'attribute2'], ['value1', 'value2']];

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = props;
    }

    render() {
        return (
            <PivotTableUI
                data={data}
                onChange={s => this.setState(s)}
                renderers={Object.assign({}, TableRenderers, PlotlyRenderers)}
                {...this.state}
            />
        );
    }
}

ReactDOM.render(<App />, document.body);

With external plotly.js

If you would rather not install and bundle plotly.js but rather get it into your app via something like <script> tag, you can ignore react-plotly.js' peer-dependcy warning and handle the dependency injection like this:

import React from 'react';
import PivotTableUI from 'react-pivottable/PivotTableUI';
import 'react-pivottable/pivottable.css';
import TableRenderers from 'react-pivottable/TableRenderers';
import createPlotlyComponent from 'react-plotly.js/factory';
import createPlotlyRenderers from 'react-pivottable/PlotlyRenderers';

// create Plotly React component via dependency injection
const Plot = createPlotlyComponent(window.Plotly);

// create Plotly renderers via dependency injection
const PlotlyRenderers = createPlotlyRenderers(Plot);

// see documentation for supported input formats
const data = [['attribute', 'attribute2'], ['value1', 'value2']];

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = props;
    }

    render() {
        return (
            <PivotTableUI
                data={data}
                onChange={s => this.setState(s)}
                renderers={Object.assign({}, TableRenderers, PlotlyRenderers)}
                {...this.state}
            />
        );
    }
}

ReactDOM.render(<App />, document.body);

Properties and layered architecture

  • <PivotTableUI {...props} />
    • <PivotTable {...props} />
      • <Renderer {...props} />
        • PivotData(props)

The interactive component provided by react-pivottable is PivotTableUI, but output rendering is delegated to the non-interactive PivotTable component, which accepts a subset of its properties. PivotTable can be invoked directly and is useful for outputting non-interactive saved snapshots of PivotTableUI configurations. PivotTable in turn delegates to a specific renderer component, such as the default TableRenderer, which accepts a subset of the same properties. Finally, most renderers will create non-React PivotData object to handle the actual computations, which also accepts a subset of the same props as the rest of the stack.

Here is a table of the properties accepted by this stack, including an indication of which layer consumes each, from the bottom up:

LayerKey & TypeDefault ValueDescription
PivotDatadata
see below for formats
(none, required)data to be summarized
PivotDatarows
array of strings
[]attribute names to prepopulate in row area
PivotDatacols
array of strings
[]attribute names to prepopulate in cols area
PivotDatavals
array of strings
[]attribute names used as arguments to aggregator (gets passed to aggregator generating function)
PivotDataaggregators
object of functions
aggregators from Utilitesdictionary of generators for aggregation functions in dropdown (see original PivotTable.js documentation)
PivotDataaggregatorName
string
first key in aggregatorskey to aggregators object specifying the aggregator to use for computations
PivotDatavalueFilter
object of arrays of strings
{}object whose keys are attribute names and values are objects of attribute value-boolean pairs which denote records to include or exclude from computation and rendering; used to prepopulate the filter menus that appear on double-click
PivotDatasorters
object or function
{}accessed or called with an attribute name and can return a function which can be used as an argument to array.sort for output purposes. If no function is returned, the default sorting mechanism is a built-in "natural sort" implementation. Useful for sorting attributes like month names, see original PivotTable.js example 1 and original PivotTable.js example 2.
PivotDatarowOrder
string
"key_a_to_z"the order in which row data is provided to the renderer, must be one of "key_a_to_z", "value_a_to_z", "value_z_to_a", ordering by value orders by row total
PivotDatacolOrder
string
"key_a_to_z"the order in which column data is provided to the renderer, must be one of "key_a_to_z", "value_a_to_z", "value_z_to_a", ordering by value orders by column total
PivotDataderivedAttributes
object of functions
{}defines derived attributes (see original PivotTable.js documentation)
Renderer<any>(none, optional)Renderers may accept any additional properties
PivotTablerenderers
object of functions
TableRenderersdictionary of renderer components
PivotTablerendererName
string
first key in rendererskey to renderers object specifying the renderer to use
PivotTableUIonChange
function
(none, required)function called every time anything changes in the UI, with the new value of the properties needed to render the new state. This function must be hooked into a state-management system in order for the "dumb" PivotTableUI component to work.
PivotTableUIhiddenAttributes
array of strings
[]contains attribute names to omit from the UI
PivotTableUIhiddenFromAggregators
array of strings
[]contains attribute names to omit from the aggregator arguments dropdowns
PivotTableUIhiddenFromDragDrop
array of strings
[]contains attribute names to omit from the drag'n'drop portion of the UI
PivotTableUImenuLimit
integer
500maximum number of values to list in the double-click menu
PivotTableUIunusedOrientationCutoff
integer
85If the attributes' names' combined length in characters exceeds this value then the unused attributes area will be shown vertically to the left of the UI instead of horizontally above it. 0 therefore means 'always vertical', and Infinity means 'always horizontal'.

Accepted formats for data

Arrays of objects

One object per record, the object's keys are the attribute names.

Note: missing attributes or attributes with a value of null are treated as if the value was the string "null".

const data = [
    {
        attr1: 'value1_attr1',
        attr2: 'value1_attr2',
        //...
    },
    {
        attr1: 'value2_attr1',
        attr2: 'value2_attr2',
        //...
    },
    //...
];

Arrays of arrays

One sub-array per record, the first sub-array contains the attribute names. If subsequent sub-arrays are shorter than the first one, the trailing values are treated as if they contained the string value "null". If subsequent sub-arrays are longer than the first one, excess values are ignored. This format is compatible with the output of CSV parsing libraries like PapaParse.

const data = [
    ['attr1', 'attr2'],
    ['value1_attr1', 'value1_attr2'],
    ['value2_attr1', 'value2_attr2'],
    //...
];

Functions that call back

The function will be called with a callback that takes an object as a parameter.

Note: missing attributes or attributes with a value of null are treated as if the value was the string "null".

const data = function(callback) {
    callback({
        "attr1": "value1_attr1",
        "attr2": "value1_attr2",
        //...
    });
    callback({
        "attr1": "value2_attr1",
        "attr2": "value2_attr2",
        //...
    };
    //...
};

NPM DownloadsLast 30 Days