react-pivottable

repository·master·Indexed 21 days ago

https://github.com/plotly/react-pivottable

A React-based library providing a drag-and-drop user interface for data exploration and analysis. It allows users to summarize datasets into pivot tables or Plotly charts using a layered architecture consisting of PivotTableUI, PivotTable, Renderer, and PivotData. Version 0.11.1 supports multiple data formats including arrays of objects, arrays of arrays, and callback functions.

Tokens
5.3K
Snippets
14
Records
17
Agent score
76%

What's inside react-pivottable

  1. Understand the react-pivottable layered architecture

    master

    The library is organized into a hierarchy of components, where each layer delegates specific responsibilities. This allows you to use the full interactive UI or just render static snapshots of data.

    1. PivotTableUI: The top-level interactive component providing the drag-and-drop interface. It is a "dumb" component and requires an onChange handler to manage state.
    2. PivotTable: A non-interactive component used for outputting saved snapshots of a configuration. It delegates rendering to a specific renderer.
    3. Renderer: A component (like TableRenderer) that handles the visual output. Renderers can accept additional custom properties.
    4. PivotData: The bottom layer that performs the actual mathematical computations and data summarization. It is a non-React object used by most renderers.
    <PivotTableUI {...props} />
      <PivotTable {...props} />
        <Renderer {...props} />
          PivotData(props)
  2. Install react-pivottable with Plotly chart support

    master

    To enable Plotly chart rendering within the pivot table, you must install react-plotly.js and plotly.js in addition to the core dependencies.

    npm install --save react-pivottable react-plotly.js plotly.js react react-dom
  3. Configure Table Heatmap modes

    master

    When using the heatmap renderers, the color scaling behavior is determined by the heatmapMode option passed during renderer creation. While the end-user typically selects a pre-configured renderer from the exported object, the underlying logic supports three modes:

    • full: The color scale is calculated using all values in the pivot table.
    • col: Each column has its own independent color scale.
    • row: Each row has its own independent color scale.

    Additionally, you can provide a custom tableColorScaleGenerator prop to the renderer to define how values map to colors.

  4. Use PivotTableUI with Plotly charts

    master

    To include Plotly charts as renderers, use createPlotlyRenderers to inject the react-plotly.js component. You then merge these new renderers with the standard TableRenderers and pass them to the renderers prop of PivotTableUI.

    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);
  5. Use PivotTableUI with external plotly.js via script tag

    master

    If you prefer to load plotly.js via a <script> tag (e.g., from a CDN) instead of bundling it with Webpack, you can use react-plotly.js/factory to create a Plotly component from the global window.Plotly object, and then inject that into createPlotlyRenderers.

    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);
  6. Use PivotTableUI for basic Table output

    master

    The PivotTableUI component is a stateless (dumb) component. To maintain the pivot table's state (such as selected rows, columns, and aggregations), you must manage the state in a parent component and pass it back into PivotTableUI via the onChange callback and spread props.

    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);
  7. Reference properties for PivotData, PivotTable, and PivotTableUI

    master

    The following table lists the properties accepted across the component stack. Note that properties are consumed by specific layers (from the bottom up).

    LayerKey & TypeDefaultDescription
    PivotDatadata (required)(none)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
    PivotDataaggregators (object of functions)aggregators from UtilitesDictionary of generators for aggregation functions
    PivotDataaggregatorName (string)first key in aggregatorsKey specifying the aggregator to use
    PivotDatavalueFilter (object of arrays){}Filters for attribute values (used in double-click menus)
    PivotDatasorters (object or function){}Custom sorting logic for attributes
    PivotDatarowOrder (string)"key_a_to_z"Order of rows: "key_a_to_z", "value_a_to_z", or "value_z_to_a"
    PivotDatacolOrder (string)"key_a_to_z"Order of columns: "key_a_to_z", "value_a_to_z", or "value_z_to_a"
    PivotDataderivedAttributes (object of functions){}Defines derived attributes
    PivotTablerenderers (object of functions)TableRenderersDictionary of renderer components
    PivotTablerendererName (string)first key in renderersKey specifying the renderer to use
    PivotTableUIonChange (function)(none, required)Function called on UI changes; must be hooked into state management
    PivotTableUIhiddenAttributes (array of strings)[]Attribute names to omit from the UI
    PivotTableUIhiddenFromAggregators (array of strings)[]Attribute names to omit from aggregator dropdowns
    PivotTableUIhiddenFromDragDrop (array of strings)[]Attribute names to omit from drag'n'drop area
    PivotTableUImenuLimit (integer)500Max values to list in the double-click menu
    PivotTableUIunusedOrientationCutoff (integer)85Threshold for switching unused attributes area between vertical and horizontal layout
  8. Supported data formats for the `data` prop

    master

    The data property (required by PivotData) accepts three distinct formats:

    1. Arrays of Objects

    One object per record. Keys are attribute names. Missing or null attributes are treated as the string "null".

    2. Arrays of Arrays

    Compatible with CSV parsing (e.g., PapaParse). The first sub-array contains attribute names. Subsequent sub-arrays are records. Shorter sub-arrays result in "null" values; longer sub-arrays have excess values ignored.

    3. Callback Functions

    A function that accepts a callback. The callback is invoked with an object representing a record. Missing or null attributes are treated as "null".

    // Array of Objects
    const data = [
        { attr1: 'val1', attr2: 'val2' },
        { attr1: 'val3', attr2: 'val4' }
    ];
    
    // Array of Arrays
    const data = [
        ['attr1', 'attr2'],
        ['val1', 'val2'],
        ['val3', 'val4']
    ];
    
    // Callback Function
    const data = function(callback) {
        callback({ "attr1": "val1", "attr2": "val2" });
        callback({ "attr1": "val3", "attr2": "val4" });
    };
  9. Create Plotly renderers with createPlotlyRenderers

    master

    To enable Plotly chart visualizations within react-pivottable, use the createPlotlyRenderers function. This function accepts a PlotlyComponent (typically from react-plotly.js) and returns an object containing several pre-configured renderer components. Each component in the returned object is a React component that can be used as a renderer for the pivot table.

    Available renderers include:

    • Grouped Column Chart
    • Stacked Column Chart
    • Grouped Bar Chart
    • Stacked Bar Chart
    • Line Chart
    • Dot Chart
    • Area Chart
    • Scatter Chart
    • Multiple Pie Chart
    import createPlotlyRenderers from './PlotlyRenderers';
    import Plot from 'react-plotly.js';
    
    const renderers = createPlotlyRenderers(Plotly);
    // 'renderers' now contains React components for each chart type.
  10. Implement click callbacks in Table renderers

    master

    You can add interactivity to the HTML table cells by providing a clickCallback within the tableOptions prop.

    When a cell (including totals) is clicked, the callback is invoked with the following arguments:

    1. event: The original click event.
    2. value: The aggregated value of the cell.
    3. filters: An object containing the attribute names and their corresponding values for that specific row/column intersection.
    4. pivotData: The PivotData instance.

    This allows you to implement features like drilling down into data or filtering a global state based on a table selection.

    const tableOptions = {
      clickCallback: (e, value, filters, pivotData) => {
        console.log('Cell clicked:', value);
        console.log('Filters for this cell:', filters);
      }
    };
    
    // Pass this to your Table renderer component
    <renderers.Table tableOptions={tableOptions} />
  11. Use the PivotTable component

    master

    The PivotTable component is the main entry point for rendering pivot tables. It uses a layered architecture where it selects a specific renderer from a renderers object based on the rendererName prop.

    By default, it uses Table as the renderer and provides a set of standard table renderers via TableRenderers. You can extend or change the UI by providing your own mapping of names to renderer components in the renderers prop.

    import PivotTable from 'react-pivottable';
    
    // Basic usage with default Table renderer
    <PivotTable
      data={myData}
      rows={['column_name']}
      cols={['column_name']}
      aggregator={myAggregator}
    />
    
    // Customizing renderers (e.g., adding a Plotly chart renderer)
    <PivotTable
      data={myData}
      renderers={{
        Table: TableRenderer,
        PlotlyChart: PlotlyRenderer
      }}
      rendererName="PlotlyChart"
    />