### Install react-pivottable and its React dependencies Source: https://github.com/plotly/react-pivottable/blob/master/README.md Installs the react-pivottable library along with its peer dependencies, React and ReactDOM, using npm. This is the initial step for using the library. ```bash npm install --save react-pivottable react react-dom ``` -------------------------------- ### Install react-pivottable with Plotly chart renderers Source: https://github.com/plotly/react-pivottable/blob/master/README.md Installs react-pivottable, react, react-dom, react-plotly.js, and plotly.js. This setup enables the use of Plotly charts as output renderers in addition to tables. Note the webpack build instructions for plotly.js. ```bash npm install --save react-pivottable react-plotly.js plotly.js react react-dom ``` -------------------------------- ### Table Renderers with Heatmap Example in React Source: https://context7.com/plotly/react-pivottable/llms.txt Demonstrates how to use react-pivottable's TableRenderers, specifically the 'Table Heatmap' option, with a custom color scale generator. This example shows setting up the PivotTableUI component with data, state management, and available renderers. ```jsx import React from 'react'; import PivotTableUI from 'react-pivottable/PivotTableUI'; import TableRenderers from 'react-pivottable/TableRenderers'; import 'react-pivottable/pivottable.css'; // Available TableRenderers: // - 'Table': Standard pivot table // - 'Table Heatmap': Full heatmap coloring based on all values // - 'Table Col Heatmap': Heatmap coloring per column // - 'Table Row Heatmap': Heatmap coloring per row // - 'Exportable TSV': Textarea with tab-separated values for copy/paste const data = [ { Category: 'A', Month: 'Jan', Value: 100 }, { Category: 'A', Month: 'Feb', Value: 150 }, { Category: 'B', Month: 'Jan', Value: 200 }, { Category: 'B', Month: 'Feb', Value: 175 }, ]; // Custom color scale generator for heatmaps function blueColorScale(values) { const min = Math.min(...values); const max = Math.max(...values); return (value) => { const intensity = Math.round(255 * (1 - (value - min) / (max - min))); return { backgroundColor: `rgb(${intensity}, ${intensity}, 255)` }; }; } class HeatmapDemo extends React.Component { constructor(props) { super(props); this.state = { data: data, rows: ['Category'], cols: ['Month'], aggregatorName: 'Sum', vals: ['Value'], rendererName: 'Table Heatmap', }; } render() { return ( this.setState(s)} renderers={TableRenderers} tableColorScaleGenerator={blueColorScale} {...this.state} /> ); } } export default HeatmapDemo; ``` -------------------------------- ### Programmatic Pivot Table Data Aggregation with PivotData Class Source: https://context7.com/plotly/react-pivottable/llms.txt This example demonstrates the direct use of the `PivotData` class from `react-pivottable/Utilities` for programmatic pivot table generation. It shows how to initialize `PivotData` with raw data and configuration, retrieve row and column keys, access aggregated values for specific cells, calculate row totals and grand totals, and iterate through records matching specific filters. ```jsx import { PivotData, aggregators } from 'react-pivottable/Utilities'; const salesData = [ { Region: 'North', Product: 'A', Sales: 100 }, { Region: 'North', Product: 'B', Sales: 150 }, { Region: 'South', Product: 'A', Sales: 200 }, { Region: 'South', Product: 'B', Sales: 175 }, { Region: 'East', Product: 'A', Sales: 125 }, ]; // Create PivotData instance for programmatic access const pivotData = new PivotData({ data: salesData, rows: ['Region'], cols: ['Product'], aggregatorName: 'Sum', vals: ['Sales'], aggregators: aggregators, }); // Get row and column keys const rowKeys = pivotData.getRowKeys(); const colKeys = pivotData.getColKeys(); console.log('Row keys:', rowKeys); // [['East'], ['North'], ['South']] console.log('Col keys:', colKeys); // [['A'], ['B']] // Get aggregated values rowKeys.forEach(rowKey => { colKeys.forEach(colKey => { const aggregator = pivotData.getAggregator(rowKey, colKey); console.log(`${rowKey} x ${colKey}: ${aggregator.value()}`); }); }); // Get row totals rowKeys.forEach(rowKey => { const rowTotal = pivotData.getAggregator(rowKey, []); console.log(`${rowKey} total: ${rowTotal.value()}`); }); // Get grand total const grandTotal = pivotData.getAggregator([], []); console.log('Grand total:', grandTotal.value()); // Iterate through matching records with filters pivotData.forEachMatchingRecord( { Region: 'North' }, (record) => console.log('North record:', record) ); ``` -------------------------------- ### Basic react-pivottable UI with Table output in React Source: https://github.com/plotly/react-pivottable/blob/master/README.md Demonstrates the basic usage of react-pivottable's PivotTableUI component for displaying data in a table format. It requires React, ReactDOM, and the library's CSS. The PivotTableUI is a stateless component that relies on parent state management. ```javascript 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 ( this.setState(s)} {...this.state} /> ); } } ReactDOM.render(, document.body); ``` -------------------------------- ### Render Interactive Pivot Table with PivotTableUI Source: https://context7.com/plotly/react-pivottable/llms.txt Demonstrates how to use the PivotTableUI component to create an interactive pivot table. This component requires external state management via the onChange callback. It takes data, row/column configurations, and aggregator settings as props. ```jsx import React from 'react'; import ReactDOM from 'react-dom'; import PivotTableUI from 'react-pivottable/PivotTableUI'; import 'react-pivottable/pivottable.css'; // Data as array of objects const salesData = [ { Region: 'North', Product: 'Widget', Sales: 1000, Quarter: 'Q1' }, { Region: 'North', Product: 'Gadget', Sales: 1500, Quarter: 'Q1' }, { Region: 'South', Product: 'Widget', Sales: 800, Quarter: 'Q1' }, { Region: 'South', Product: 'Gadget', Sales: 1200, Quarter: 'Q2' }, { Region: 'East', Product: 'Widget', Sales: 900, Quarter: 'Q2' }, { Region: 'West', Product: 'Gadget', Sales: 1100, Quarter: 'Q2' }, ]; class SalesAnalysis extends React.Component { constructor(props) { super(props); this.state = { data: salesData, rows: ['Region'], cols: ['Product'], aggregatorName: 'Sum', vals: ['Sales'], }; } render() { return ( this.setState(s)} rows={this.state.rows} cols={this.state.cols} aggregatorName={this.state.aggregatorName} vals={this.state.vals} hiddenAttributes={['Quarter']} menuLimit={500} unusedOrientationCutoff={85} {...this.state} /> ); } } ReactDOM.render(, document.getElementById('root')); ``` -------------------------------- ### Custom Aggregators with Number Formatting in React Source: https://context7.com/plotly/react-pivottable/llms.txt Demonstrates creating custom aggregators in react-pivottable, such as 'Euro Sum' and 'Euro Average', by utilizing the `numberFormat` utility for locale-specific currency formatting. This allows for tailored data aggregation and presentation within pivot tables. ```jsx import React from 'react'; import PivotTableUI from 'react-pivottable/PivotTableUI'; import { aggregators, aggregatorTemplates, numberFormat } from 'react-pivottable/Utilities'; import 'react-pivottable/pivottable.css'; // Create custom number formatter const euroFormat = numberFormat({ digitsAfterDecimal: 2, thousandsSep: '.', decimalSep: ',', prefix: '€', }); // Create custom aggregator using templates const customAggregators = Object.assign({}, aggregators, { 'Euro Sum': aggregatorTemplates.sum(euroFormat), 'Euro Average': aggregatorTemplates.average(euroFormat), }); const salesData = [ { Product: 'Laptop', Region: 'Europe', Amount: 1200.50 }, { Product: 'Laptop', Region: 'Asia', Amount: 980.25 }, { Product: 'Phone', Region: 'Europe', Amount: 650.00 }, { Product: 'Phone', Region: 'Asia', Amount: 720.75 }, ]; class CustomAggregatorDemo extends React.Component { constructor(props) { super(props); this.state = { data: salesData, rows: ['Product'], cols: ['Region'], aggregatorName: 'Euro Sum', vals: ['Amount'], }; } render() { return ( this.setState(s)} aggregators={customAggregators} {...this.state} /> ); } } export default CustomAggregatorDemo; ``` -------------------------------- ### Render Static Pivot Table with PivotTable Source: https://context7.com/plotly/react-pivottable/llms.txt Illustrates the use of the non-interactive PivotTable component for displaying static pivot table reports. This is suitable for rendering saved configurations without user interaction. It requires data and pivot table configuration props. ```jsx import React from 'react'; import PivotTable from 'react-pivottable/PivotTable'; import 'react-pivottable/pivottable.css'; const data = [ { Category: 'Electronics', Month: 'Jan', Revenue: 5000 }, { Category: 'Electronics', Month: 'Feb', Revenue: 6200 }, { Category: 'Clothing', Month: 'Jan', Revenue: 3000 }, { Category: 'Clothing', Month: 'Feb', Revenue: 3500 }, { Category: 'Food', Month: 'Jan', Revenue: 2000 }, { Category: 'Food', Month: 'Feb', Revenue: 2100 }, ]; function StaticPivotReport() { return ( ); } export default StaticPivotReport; ``` -------------------------------- ### PivotTable Component Properties Source: https://github.com/plotly/react-pivottable/blob/master/README.md Details the properties for the PivotTable component, including renderers and renderer selection. ```APIDOC ## PivotTable Component ### Description The PivotTable component displays pivot table data and allows customization through renderers. ### Method N/A (Component properties) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body ##### `renderers` (object of functions) - **Type**: object - **Required**: No - **Default**: `TableRenderers` - **Description**: A dictionary of renderer components available for the pivot table. ##### `rendererName` (string) - **Type**: string - **Required**: No - **Default**: First key in `renderers` object - **Description**: The key corresponding to the renderer component to be used for displaying the pivot table. ### Request Example ```json { "renderers": { "Table": PivotTableComponent.TableRenderers.Table, "Chart": PivotTableComponent.ChartRenderers.Plotlytreemap }, "rendererName": "Table" } ``` ### Response #### Success Response (200) N/A (Component rendering) #### Response Example N/A ``` -------------------------------- ### Supported Data Input Formats for Pivot Table Source: https://context7.com/plotly/react-pivottable/llms.txt The library supports three primary data input formats: arrays of objects, arrays of arrays (CSV-compatible), and callback functions for streaming data. This flexibility allows integration with various data sources and loading strategies. ```jsx import React from 'react'; import PivotTableUI from 'react-pivottable/PivotTableUI'; import 'react-pivottable/pivottable.css'; // Format 1: Array of objects (most common) const objectData = [ { name: 'Alice', department: 'Engineering', salary: 75000 }, { name: 'Bob', department: 'Sales', salary: 65000 }, { name: 'Carol', department: 'Engineering', salary: 80000 }, ]; // Format 2: Array of arrays (CSV-compatible, works with PapaParse output) const arrayData = [ ['name', 'department', 'salary'], ['Alice', 'Engineering', 75000], ['Bob', 'Sales', 65000], ['Carol', 'Engineering', 80000], ]; // Format 3: Callback function for streaming/lazy data const callbackData = function(callback) { callback({ name: 'Alice', department: 'Engineering', salary: 75000 }); callback({ name: 'Bob', department: 'Sales', salary: 65000 }); callback({ name: 'Carol', department: 'Engineering', salary: 80000 }); }; class MultiFormatDemo extends React.Component { constructor(props) { super(props); this.state = { data: objectData }; // Can use any format } render() { return ( this.setState(s)} {...this.state} /> ); } } export default MultiFormatDemo; ``` -------------------------------- ### Create Plotly Renderers with Bundled Plotly.js Source: https://context7.com/plotly/react-pivottable/llms.txt This snippet demonstrates how to create Plotly.js chart renderers by injecting the Plotly component. It supports various chart types like bar, line, area, scatter, and pie charts. This method assumes Plotly.js is bundled with your project. ```jsx import React from 'react'; import PivotTableUI from 'react-pivottable/PivotTableUI'; import TableRenderers from 'react-pivottable/TableRenderers'; import Plot from 'react-plotly.js'; import createPlotlyRenderers from 'react-pivottable/PlotlyRenderers'; import 'react-pivottable/pivottable.css'; // Create Plotly renderers via dependency injection const PlotlyRenderers = createPlotlyRenderers(Plot); // Available renderers after merge: // - Table, Table Heatmap, Table Col Heatmap, Table Row Heatmap, Exportable TSV // - Grouped Column Chart, Stacked Column Chart, Grouped Bar Chart, Stacked Bar Chart // - Line Chart, Dot Chart, Area Chart, Scatter Chart, Multiple Pie Chart const data = [ { Year: '2022', Quarter: 'Q1', Sales: 12000, Profit: 3000 }, { Year: '2022', Quarter: 'Q2', Sales: 15000, Profit: 4500 }, { Year: '2022', Quarter: 'Q3', Sales: 18000, Profit: 5400 }, { Year: '2023', Quarter: 'Q1', Sales: 14000, Profit: 3800 }, { Year: '2023', Quarter: 'Q2', Sales: 17000, Profit: 5100 }, ]; class ChartablePivot extends React.Component { constructor(props) { super(props); this.state = { data: data, rendererName: 'Grouped Column Chart', rows: ['Year'], cols: ['Quarter'], aggregatorName: 'Sum', vals: ['Sales'], plotlyOptions: { width: 800, height: 500 }, plotlyConfig: { displayModeBar: true }, }; } render() { return ( this.setState(s)} renderers={Object.assign({}, TableRenderers, PlotlyRenderers)} {...this.state} /> ); } } export default ChartablePivot; ``` -------------------------------- ### react-pivottable UI with Plotly charts and Table output in React Source: https://github.com/plotly/react-pivottable/blob/master/README.md Integrates Plotly renderers with react-pivottable by injecting the react-plotly.js component. This allows for both table and Plotly chart outputs. It requires importing TableRenderers and creating PlotlyRenderers using createPlotlyRenderers. ```javascript 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 ( this.setState(s)} renderers={Object.assign({}, TableRenderers, PlotlyRenderers)} {...this.state} /> ); } } ReactDOM.render(, document.body); ``` -------------------------------- ### PivotTableUI Component Properties Source: https://github.com/plotly/react-pivottable/blob/master/README.md Details the properties for the PivotTableUI component, focusing on user interface configuration and state management. ```APIDOC ## PivotTableUI Component ### Description The PivotTableUI component provides an interactive user interface for pivot table configuration and updates. ### Method N/A (Component properties) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body ##### `onChange` (function) - **Type**: function - **Required**: Yes - **Default**: (none) - **Description**: A callback function that is invoked whenever any change occurs in the UI. It receives the new properties required to render the updated state and must be integrated with a state-management system. ##### `hiddenAttributes` (array of strings) - **Type**: array of strings - **Required**: No - **Default**: `[]` - **Description**: An array containing the names of attributes to be hidden from the UI. ##### `hiddenFromAggregators` (array of strings) - **Type**: array of strings - **Required**: No - **Default**: `[]` - **Description**: An array containing the names of attributes to be omitted from the aggregator arguments dropdowns. ### Request Example ```json { "onChange": "function(props) { ... }", "hiddenAttributes": ["attribute1", "attribute2"], "hiddenFromAggregators": ["attribute3"] } ``` ### Response #### Success Response (200) N/A (Component rendering) #### Response Example N/A ``` -------------------------------- ### Create Plotly Component from External Script Tag Source: https://context7.com/plotly/react-pivottable/llms.txt This method allows using Plotly.js loaded via a script tag, suitable for projects that avoid bundling. It uses a factory pattern to create the Plot component from the global `window.Plotly` object. Ensure the Plotly.js CDN script is included in your HTML. ```jsx import React from 'react'; import PivotTableUI from 'react-pivottable/PivotTableUI'; import TableRenderers from 'react-pivottable/TableRenderers'; import createPlotlyComponent from 'react-plotly.js/factory'; import createPlotlyRenderers from 'react-pivottable/PlotlyRenderers'; import 'react-pivottable/pivottable.css'; // Create Plot component from globally loaded Plotly // Requires: const Plot = createPlotlyComponent(window.Plotly); const PlotlyRenderers = createPlotlyRenderers(Plot); class ExternalPlotlyPivot extends React.Component { constructor(props) { super(props); this.state = props; } render() { return ( this.setState(s)} renderers={Object.assign({}, TableRenderers, PlotlyRenderers)} {...this.state} /> ); } } export default ExternalPlotlyPivot; ``` -------------------------------- ### react-pivottable UI with external plotly.js in React Source: https://github.com/plotly/react-pivottable/blob/master/README.md Configures react-pivottable to use an externally loaded plotly.js (e.g., via a script tag) instead of bundling it. This approach uses createPlotlyComponent to inject the global Plotly object and createPlotlyRenderers for the renderers. ```javascript 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 ( this.setState(s)} renderers={Object.assign({}, TableRenderers, PlotlyRenderers)} {...this.state} /> ); } } ReactDOM.render(, document.body); ``` -------------------------------- ### PivotData Component Properties Source: https://github.com/plotly/react-pivottable/blob/master/README.md Details the properties accepted by the PivotData component, focusing on derived attributes. ```APIDOC ## PivotData Component ### Description The PivotData component is used to define derived attributes for data manipulation. ### Method N/A (Component properties) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body ##### `derivedAttributes` (object of functions) - **Type**: object - **Required**: No - **Default**: `{}` - **Description**: An object containing functions that define derived attributes. Refer to the [original PivotTable.js documentation](https://github.com/nicolaskruchten/pivottable/wiki/Derived-Attributes) for more details. ### Request Example ```json { "derivedAttributes": { "exampleAttribute": function(mp) { return mp.value1 + mp.value2; } } } ``` ### Response #### Success Response (200) N/A (Component rendering) #### Response Example N/A ``` -------------------------------- ### PivotData Component Props Source: https://github.com/plotly/react-pivottable/blob/master/README.md This section details the various props available for the PivotData component, which is the core of the React PivotTable. ```APIDOC ## PivotData Component Props ### Description This section details the various props available for the PivotData component, which is the core of the React PivotTable. ### Method N/A (Component Props) ### Endpoint N/A (Component Props) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ## PivotData Props Details ### `vals` - **Type**: array of strings - **Default**: `[]` - **Description**: Attribute names used as arguments to the aggregator. These are passed to the aggregator generating function. ### `aggregators` - **Type**: object of functions - **Default**: `aggregators` from `Utilities` - **Description**: A dictionary of generators for aggregation functions displayed in the dropdown. Refer to the [original PivotTable.js documentation](https://github.com/nicolaskruchten/pivottable/wiki/Aggregators) for more details. ### `aggregatorName` - **Type**: string - **Default**: The first key in the `aggregators` object. - **Description**: The key to the `aggregators` object specifying which aggregator to use for computations. ### `valueFilter` - **Type**: object of arrays of strings - **Default**: `{}` - **Description**: An object where keys are attribute names and values are objects of attribute value-boolean pairs. This denotes records to include or exclude from computation and rendering. It's used to prepopulate the filter menus that appear on double-click. ### `sorters` - **Type**: object or function - **Default**: `{}` - **Description**: This prop can be accessed or called with an attribute name and can return a function suitable for `Array.prototype.sort`. If no function is returned, a default "natural sort" implementation is used. This is useful for sorting attributes like month names. See [original PivotTable.js example 1](http://nicolas.kruchten.com/pivottable/examples/mps_agg.html) and [original PivotTable.js example 2](http://nicolas.kruchten.com/pivottable/examples/montreal_2014.html). ### `rowOrder` - **Type**: string - **Default**: `"key_a_to_z"` - **Description**: Specifies 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 sorts by the row total. ### `colOrder` - **Type**: string - **Default**: `"key_a_to_z"` - **Description**: Specifies 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 sorts by the column total. ``` -------------------------------- ### Derived Attributes for Data Transformation in React Source: https://context7.com/plotly/react-pivottable/llms.txt Illustrates the use of `derivers` in react-pivottable to create computed attributes from existing data, including built-in functions for date formatting and numeric binning. Custom deriver functions can also be defined for more complex data transformations. ```jsx import React from 'react'; import PivotTableUI from 'react-pivottable/PivotTableUI'; import { derivers } from 'react-pivottable/Utilities'; import 'react-pivottable/pivottable.css'; const transactionData = [ { date: '2023-01-15', amount: 150, customer: 'A001' }, { date: '2023-02-20', amount: 275, customer: 'B002' }, { date: '2023-03-10', amount: 89, customer: 'A001' }, { date: '2023-04-05', amount: 420, customer: 'C003' }, { date: '2023-05-18', amount: 185, customer: 'B002' }, ]; // Define derived attributes const derivedAttributes = { // Built-in date formatter: %y=year, %m=month, %n=month name, %d=day, %w=weekday 'Month': derivers.dateFormat('date', '%n %y'), 'Day of Week': derivers.dateFormat('date', '%w'), 'Year-Month': derivers.dateFormat('date', '%y-%m'), // Built-in binning: groups numeric values 'Amount Range': derivers.bin('amount', 100), // bins of 100 // Custom deriver function 'Amount Category': function(record) { if (record.amount < 100) return 'Small'; if (record.amount < 300) return 'Medium'; return 'Large'; }, }; class DerivedAttributesDemo extends React.Component { constructor(props) { super(props); this.state = { data: transactionData, derivedAttributes: derivedAttributes, rows: ['Amount Category'], cols: ['Month'], aggregatorName: 'Sum', vals: ['amount'], }; } render() { return ( this.setState(s)} {...this.state} /> ); } } export default DerivedAttributesDemo; ``` -------------------------------- ### Callback Function Data Format for PivotTable Source: https://github.com/plotly/react-pivottable/blob/master/README.md This format accepts a function that takes a callback as an argument. The callback is invoked with an object representing a record. Missing or null attributes are treated as the string 'null'. ```javascript const data = function(callback) { callback({ "attr1": "value1_attr1", "attr2": "value1_attr2", //... }); callback({ "attr1": "value2_attr1", "attr2": "value2_attr2", //... }; //... }; ``` -------------------------------- ### Custom Sorters for Categorical Data in React-Pivottable Source: https://context7.com/plotly/react-pivottable/llms.txt Defines custom sort orders for attributes, enabling logical sorting of categorical data like months or days. It utilizes the `sortAs` utility from `react-pivottable/Utilities` to specify desired orderings. This is useful when default alphabetical sorting is not appropriate for the data. ```jsx import React from 'react'; import PivotTableUI from 'react-pivottable/PivotTableUI'; import { sortAs } from 'react-pivottable/Utilities'; import 'react-pivottable/pivottable.css'; const eventData = [ { Day: 'Friday', Meal: 'Dinner', Attendees: 45 }, { Day: 'Saturday', Meal: 'Lunch', Attendees: 30 }, { Day: 'Thursday', Meal: 'Dinner', Attendees: 25 }, { Day: 'Sunday', Meal: 'Lunch', Attendees: 55 }, { Day: 'Friday', Meal: 'Lunch', Attendees: 35 }, { Day: 'Saturday', Meal: 'Dinner', Attendees: 60 }, ]; // Define custom sort orders using sortAs utility const customSorters = { // Sort days in logical order instead of alphabetically Day: sortAs(['Thursday', 'Friday', 'Saturday', 'Sunday']), // Sort meals in logical order Meal: sortAs(['Lunch', 'Dinner']), }; // Alternative: function-based sorter const sorterFunction = function(attr) { if (attr === 'Day') { return sortAs(['Thursday', 'Friday', 'Saturday', 'Sunday']); } if (attr === 'Meal') { return sortAs(['Lunch', 'Dinner']); } return null; // Use default natural sort }; class CustomSorterDemo extends React.Component { constructor(props) { super(props); this.state = { data: eventData, rows: ['Day'], cols: ['Meal'], aggregatorName: 'Sum', vals: ['Attendees'], sorters: customSorters, rowOrder: 'key_a_to_z', // Options: 'key_a_to_z', 'value_a_to_z', 'value_z_to_a' colOrder: 'key_a_to_z', }; } render() { return ( this.setState(s)} {...this.state} /> ); } } export default CustomSorterDemo; ``` -------------------------------- ### Handle Table Cell Clicks with React-PivotTable Source: https://context7.com/plotly/react-pivottable/llms.txt This snippet demonstrates how to attach a click callback to table cells in a react-pivottable component. The callback function `handleCellClick` receives event details, cell value, filters, and the pivot data object. It then processes matching records and updates the component's state to display selected orders, enabling drill-down or custom interactions. ```jsx import React from 'react'; import PivotTableUI from 'react-pivottable/PivotTableUI'; import TableRenderers from 'react-pivottable/TableRenderers'; import 'react-pivottable/pivottable.css'; const orderData = [ { Customer: 'Acme Corp', Product: 'Widget', OrderId: 'ORD001', Amount: 500 }, { Customer: 'Acme Corp', Product: 'Gadget', OrderId: 'ORD002', Amount: 750 }, { Customer: 'Tech Inc', Product: 'Widget', OrderId: 'ORD003', Amount: 300 }, { Customer: 'Tech Inc', Product: 'Widget', OrderId: 'ORD004', Amount: 450 }, { Customer: 'Global Co', Product: 'Gadget', OrderId: 'ORD005', Amount: 600 }, ]; class ClickCallbackDemo extends React.Component { constructor(props) { super(props); this.state = { data: orderData, rows: ['Customer'], cols: ['Product'], aggregatorName: 'Sum', vals: ['Amount'], selectedRecords: [], }; } handleCellClick = (e, value, filters, pivotData) => { // Collect matching records based on clicked cell's filters const matchingRecords = []; pivotData.forEachMatchingRecord(filters, (record) => { matchingRecords.push(record); }); // Display or process the records console.log('Cell value:', value); console.log('Filters:', filters); console.log('Matching records:', matchingRecords); this.setState({ selectedRecords: matchingRecords }); alert(`Found ${matchingRecords.length} orders:\n${matchingRecords.map(r => r.OrderId).join(', ')}`); }; render() { return (
this.setState(s)} renderers={TableRenderers} tableOptions={{ clickCallback: this.handleCellClick, }} {...this.state} /> {this.state.selectedRecords.length > 0 && (

Selected Records:

{JSON.stringify(this.state.selectedRecords, null, 2)}
)}
); } } export default ClickCallbackDemo; ``` -------------------------------- ### Array of Arrays Data Format for PivotTable Source: https://github.com/plotly/react-pivottable/blob/master/README.md This format uses an array of arrays, where the first sub-array contains attribute names. Subsequent sub-arrays represent records. Trailing values are treated as 'null' if shorter than the header, and excess values are ignored if longer. ```javascript const data = [ ['attr1', 'attr2'], ['value1_attr1', 'value1_attr2'], ['value2_attr1', 'value2_attr2'], //... ]; ``` -------------------------------- ### Array of Objects Data Format for PivotTable Source: https://github.com/plotly/react-pivottable/blob/master/README.md This format represents data as an array where each element is an object. The keys of the object correspond to attribute names. Missing or null attributes are treated as the string 'null'. ```javascript const data = [ { attr1: 'value1_attr1', attr2: 'value1_attr2', //... }, { attr1: 'value2_attr1', attr2: 'value2_attr2', //... }, //... ]; ``` -------------------------------- ### Value Filtering in React-Pivottable Source: https://context7.com/plotly/react-pivottable/llms.txt Filters data by excluding specific attribute values from computation and rendering using the `valueFilter` property. This allows you to selectively include or exclude data points based on their attribute values. The `valueFilter` is an object where keys are attribute names and values are objects mapping excluded values to `true`. ```jsx import React from 'react'; import PivotTableUI from 'react-pivottable/PivotTableUI'; import 'react-pivottable/pivottable.css'; const employeeData = [ { Department: 'Engineering', Level: 'Senior', Salary: 120000 }, { Department: 'Engineering', Level: 'Junior', Salary: 70000 }, { Department: 'Sales', Level: 'Senior', Salary: 95000 }, { Department: 'Sales', Level: 'Junior', Salary: 55000 }, { Department: 'Marketing', Level: 'Senior', Salary: 85000 }, { Department: 'Marketing', Level: 'Junior', Salary: 50000 }, { Department: 'HR', Level: 'Senior', Salary: 75000 }, ]; class ValueFilterDemo extends React.Component { constructor(props) { super(props); this.state = { data: employeeData, rows: ['Department'], cols: ['Level'], aggregatorName: 'Average', vals: ['Salary'], // Exclude specific values: keys are attribute names, values are objects // where each key is a value to exclude (set to true) valueFilter: { Department: { HR: true }, // Exclude HR department Level: { Junior: true }, // Exclude Junior level }, }; } render() { return ( this.setState(s)} {...this.state} /> ); } } export default ValueFilterDemo; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.