Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 1,000,000+ packages pre-installed, including @opuscapita/react-grid with all npm packages installed. Try it out:

require("prop-types/package.json"); // prop-types is a peer dependency. require("react/package.json"); // react is a peer dependency. require("react-dom/package.json"); // react-dom is a peer dependency. require("react-immutable-proptypes/package.json"); // react-immutable-proptypes is a peer dependency. require("styled-components/package.json"); // styled-components is a peer dependency. var reactGrid = require("@opuscapita/react-grid")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

@opuscapita/react-grid v9.3.4

OpusCapita react grid component

react-grid

Description

Datagrid is a component that can be used to present data in table. It supports inline edit, action bar and lot more. Component is highly customizable to meet different use cases.

Underneath it uses originally Facebook's, but later continued by Schrodinger fixed-data-table-2 react component, which is designed to handle large amounts amounts of data without sacraficing performance.

Installation

npm install @opuscapita/react-grid
npm install react-immutable-proptypes

Demo

View the DEMO

Change log

View the Change log

Migrate guide

View the Migrate guide between major versions

Redux dependency

Datagrid uses redux as data store, so you must have redux set up in your project. It also depends on redux-thunk and react-intl-redux to be present. These dependencies comes from the fact that this component is separated from another project and it is known that these dependencies should be removed at some point.

Usage

First you have to connect your component to the redux. Then you can map the datagrid's state and actions to your component's props. The mappings are needed only for those parts that you need in your component. For example if you only load data to the grid, you can only map the setData action. If you need to know currently selected items, you need to map selectedItems from the grid state.

  • Create a GRID object that contains id and idKeyPath of your grid. This object is passed to every action you call and to the Datagrid component itself as prop.
  • Create a column array that configures your grid's columns. Some actions needs this information as well.
  • Add Datagrid component to your render method and pass in the grid and columns props.
  • Then to set the data to the grid, call setData action with grid, columns and data parameters.
  • You should now have a grid with data loaded.
  • Check the API section below to see what props the Datagrid supports, also GRID object and columns are documented there.
  • To see what actions are available, check the actions file.

Responsiveness

The grid component has logic to always take the space that is available on it's container component. Make sure to determine your container's width and height! If you make your container to grow and shrink with window size, the grid will follow and take the space that is has.

Grid listens to window.resize event. If you modify container size dynamically, remember to fire window.resize event to make grid follow new size. There's also redux action forceRefresh for the convenience.

Builds

UMD

The default build with compiled styles in the .js file. Also minified version available in the lib/umd directory.

CommonJS/ES Module

You need to configure your module loader to use cjs or es fields of the package.json to use these module types. Also you need to configure sass loader, since all the styles are in sass format.

API

Datagrid

Prop nameTypeDefaultDescription
gridobjectrequiredGrid attributes and config object
columnsarrayrequiredArray of column configuration objects
rowsCountnumberOverride rows count otherwise calculated from data
idKeyPatharray of stringsKey path to unique ID value in the grid data, used in many features like row selecting and inline editing
gridHeadernodeGrid header displayed on top of grid
actionBarnodeAction bar element displayed at top right
actionBarLeftnodeAction bar element displayed at top left
cellSelectbooleanfalseEnable cell selecting
disableDropdownbooleanfalseDon't use dropdown menu in the action bar
disableFilteringControlsbooleanfalseDon't display the filtering controls (only used if disableDropdown is true)
dropdownMenuItemsarrayAdditional dropdown menu items
inlineEditbooleanfalseEnable inline editing
inlineAddbooleantrueEnable inline adding (defaults to true if inlineEdit is enabled)
filteringbooleanfalseEnable column filtering
removingbooleanfalseEnable item removing
columnSettingsbooleanfalseEnable column settings popup (column selecting and re-ordering)
rowSelectbooleanfalseEnable row selecting
rowSelectCheckboxColumnbooleanfalseEnable additional checkbox column for row selecting
multiSelectbooleanfalseEnable multi selecting on row selecting
selectComponentOptionsImmutable.MapOptions data for the react-select components
selectComponentTranslationsobjectTranslation strings for react-select placeholder and noResultsText texts.
isCreatableSelectboolWith this option it's possible to create new select options on the fly
disableActionsbooleanfalseDisable action bar actions, eg. when other grid busy
disableActionsMessageobject{ messageId: 'GridActionsDisabledOtherGridBusy' }Message about the reason of disabled action bar actions
disableActionBarbooleanfalseDisable action bar rendering
disableActionSavebooleanfalseDisable Save action button
enableArrowNavigationbooleanfalseEnable navigation with arrow keys in editing mode
onSavefunctionCallback that is called when save button is clicked
onRemovefunctionCallback that is called when delete is clicked
onCancelfunctionCallback that is called when cancel is clicked
onAddClickfunctionCallback that is called when add is clicked
onEditClickfunctionCallback that is called when edit is clicked
tabIndexnumber1tabIndex start value, needed when multiple grids on same page
extraColumnobjectExtra column that cannot be hidden or re-ordered. It's rendered always as first colunn
headerHeightnumber40Pixel height of the header row
rowHeightnumber40Pixel height of rows
containerStyleobjectAdditional styles to be set on the container div
scrollToColumnnumberIndex of column to scroll to
scrollTopnumberValue of vertical scroll
scrollToRownumberIndex of row to scroll to
scrollInEditModebooleanfalseAllow the usage of scrollToRow in edit mode
onRowClickfunctionCallback that is called when a row is clicked
onRowDoubleClickfunctionCallback that is called when a row is double clicked
onRowMouseDownfunctionCallback that is called when a mouse-down event happens on a row
onRowMouseEnterfunctionCallback that is called when a mouse-enter event happens on a row
onRowMouseLeavefunctionCallback that is called when a mouse-leave event happens on a row
onScrollStartfunctionCallback that is called when scrolling starts with current horizontal and vertical scroll values
onScrollEndfunctionCallback that is called when scrolling ends or stops with new horizontal and vertical scroll values
rowClassNameGetterfunctionTo get any additional CSS classes that should be added to a row, rowClassNameGetter(index) is called
rowHeightGetterfunctionIf specified, rowHeightGetter(rowData, rowIndex) is called for each row and the returned value overrides rowHeight for particular row
onContentHeightChangefunctionCallback that is called when rowHeightGetter returns a different height for a row than the rowHeight prop. This is necessary because initially table estimates heights of some parts of the content
showSelectAllCheckboxbooltrueShow Select all checkbox in the header when rowSelectCheckboxColumn is set to true
contextMenuItemsarrayArray of items in the context menu
paginationobjectObject of pagination options

Datagrid - grid prop attributes

Prop nameTypeDefaultDescription
idstringrequiredID of the datagrid
idKeyPatharray of stringsKey path to unique ID value in the grid data, used in many
defaultShowFilteringRowbooleanfalseShow filtering row as default
defaultSortColumnstringcolumnKey of column sorted by default. ColumnKey is joined with '/' from valueKeyPath array, if columnKey is not defined in the column props
defaultSortOrderstring'asc'Default sort order of default sort [asc/desc]
disableRememberSelectedItemsbooleanfalseDisable remembering the selected rows
disableRememberIsFilteringbooleanfalseDisable remembering is filtering ebabled
disableRememberFilterDatabooleanfalseDisable remembering the filters
disableRememberSortDatabooleanfalseDisable remembering the sorting
disableRememberColumnWidthsbooleanfalseDisable remembering the column widths
languagestring'en'Default taken from redux user state used in OC apps
regionstring'en-GB'Default taken from redux user state used in OC apps
dateFormatstring'L'Default taken from redux user state used in OC apps
thousandSeparatorstring' 'Default taken from redux user state used in OC apps
decimalSeparatorstring'.'Default taken from redux user state used in OC apps
paginationbooleanfalseTrue, if grid data is paginated. Otherwise false.

Datagrid - column prop attributes

NameTypeDefaultDescription
headernodeColumn header content
columnKeystringColumn identifier key (required if no valueKeyPath, otherwise autogenerated)
valueKeyPathstringColumn content value key path
valueTypestringValue type [text/number/float/boolean/date]
valueOptionsobjectOptions for the value rendering
componentTypestringInput component type [boolean/checkbox/currency/date/float/multiselect/number/select/text]
valueRenderfunctionOverride value render, (rowData, rowIndex) as parameters
editValueRenderfunctionOverride value render in editing mode, (rowData, rowIndex, setRef, onKeyDown) as parameters
editValueParserfunctionOverride value parser in editing mode, (value) as parameter
createValueRenderfunctionOverride value render in creating mode, (rowData, rowIndex, setRef, onKeyDown) as parameters
filterValueRenderfunctionOverride value render in filtering mode, (rowData, rowIndex) as parameters
cellfunctionOverride cell content renderer, rowIndex as parameter
cellEditfunctionOverride content renderer in editing mode
cellCreatefunctionOverride cell content renderer in creating mode
cellFilterfunctionOverride cell content renderer in filtering mode
renderComponentPropsobjectAdditional props for the render component
editComponentPropsobjectAdditional props for the edit component
createComponentPropsobjectAdditional props for the create component
filterComponentPropsobjectAdditional props for the filter component
widthnumber200The pixel width of the column
minWidthnumber20The minimum pixel width of the column
maxWidthnumberThe maximum pixel width of the column
alignnumberThe horizontal alignment of the column
fixedbooleanColumn is fixed
fixedRightbooleanColumn is fixed to right
allowCellsRecyclingbooleanRecycle cells that are outside viewport horizontally, better horizontal scrolling performance.
disableResizingbooleanDisable column resizing this column
disableSortingbooleanDisable column sorting this column
disableEditingbooleanDisable inline editing this column
flexGrownumberThe grow factor relative to other columns
valueEmptyCheckerfunctionChecker function defined when data is empty
sortValueGetterfunctionGetter function for the sort data
sortComparatorfunctionComparator function for the sort data
filterMatcherfunctionMatcher function that matches filter to data (parameters: rowData, filterValue)
defaultValuestring, numberDefault value for the item when creating new item
isRequiredboolIndicating if column value is required
isHiddenboolColumn is hidden by default and can be enabled from column settings, enable columnSettings grid prop
onValueMatchChangeValueobjectChange other column value if own value matches
disableEditingOnValueMatchobjectDisable input element of this column when value at keyPath matches
onEditValueChangefunctionCalled on edit value change, called with (value, valueKeyPath, rowIndex, dataId)
onCreateValueChangefunctionCalled on create value change, called with (value, valueKeyPath, rowIndex)
onCreateBlurfunctionCalled on create cell input blur, called with (value, rowIndex)
onEditBlurfunctionCalled on edit cell input blur, called with (value, rowIndex, dataId)
onLastCellTabPressfunctionCalled on tab keypress in edit/create cell when the last cell in the grid is being focused, called with original KeyPress event
selectComponentOptionsarrayOptions data for the react-select component
translationsobjectTranslations object
isMultiselectTooltipDisabledbooleanfalseTooltip that shows selected items in view mode
virtualizedbooleanfalseIf true and input component type is multiselect, filter option list is virtualized

Datagrid - valueOptions prop attributes for currency value type

NameTypeDefaultDescription
currencyKeyPatharray['currency']Currency code key path to calculate number of decimals from
decimalsnumberNumber of decimals
thousandSeparatorstringDefaults to datagrid config
decimalSeparatorarrayDefaults to datagrid config
currencystringDefaults to datagrid config
multipliernumberIf defined, values of columns, with componentType currency, are multiplied by multiplier in view mode. Note that in create and edit mode values are real, not multiplied.

Datagrid - onValueMatchChangeValue prop attributes

NameTypeDefaultDescription
matchValueanyWhen this columns data match to this
newValueKeyPatharray of stringsChange value at this keyPath
newValueanyThe new value to be inserted

Datagrid - disableEditingOnValueMatch prop attributes

NameTypeDefaultDescription
matchValueKeyPatharray of stringsKeypath of the value to be matched
matchValueanyThe value to be matched

Datagrid - extraColumn prop attributes

NameTypeDefaultDescription
widthnumber40Column width in pixels
valueRenderfunctionValue render function
cellEditfunctionRender function for edit mode
cellCreatefunctionRender function for create mode
cellFilterfunctionRender function for create mode
isResizablebooleanfalseIs column resisable

Datagrid - contextMenuItems prop array attributes

NameTypeDefaultDescription
idstringItem id
titleanyValue to display in the menu
iconanyIcon element to display with item
onClickfunctiononClick handles, parameters (selectedIds :: List, selectedData :: List)
disabledboolean, functionfalseIs item disabled, parameters (selectedIds :: List, selectedData :: List)

Datagrid - contextMenuItems prop array attributes

NameTypeDefaultDescription
valueanyValue to display in the menu
onClickfunctiononClick handles, parameters (selectedIds :: List, selectedData :: List)
titlestringItem title to show when mouse overing
disabledboolean, functionfalseIs item disabled, parameters (selectedIds :: List, selectedData :: List)
headerbooleanfalseIs item a header
dividerbooleanfalseIs item a divider

Datagrid - pagination prop attributes

NameTypeDefaultDescription
pageSizenumberRow count on page
totalLimitnumberLimit for total amount of rows
totalSizenumberTotal amount of rows
getDatafunctionCallback function to request paginated data, parameters (offset :: number, count :: number, filters :: Map, sortColumn :: string or number, sortOrder :: string)

Datagrid column - translations prop attributes

NameTypeDefaultDescription
columnHeaderTooltipstring or nodeSpecifies optional tooltip for column header

Code example

import React from 'react';
import { Datagrid } from '@opuscapita/react-grid';

export default class DatagridView extends React.Component {
  render() {
    const GRID = {
      id: 'accounts', // unique id for the grid
      idKeyPath: ['accountId'], // path to unique Id in the data to separate rows from eachother
    };
    const columns = [
      {
        header: 'Account Name',
        valueKeyPath: ['name'],
        valueType: 'text',
        width: 200,
      },
      {
        header: 'Account number',
        valueKeyPath: ['accountNumber'],
        valueType: 'text',
        width: 200,
      },
      {
        header: 'Amount',
        valueKeyPath: ['amount'],
        valueType: 'currency',
        valueOtions: {
          decimals: 3,
        },
        width: 200,
      },
    ];

    return (
      <Datagrid
        grid={GRID}
        columns={columns}
      />
    );
  }
}

Troubleshooting

  • Grid shows only headers, not the data.
    • Determine the height of your container with CSS. Grid will expand to it's container size!
    • If you know that your other components height in the page is 100px, you can set grid container height to calc(100% - 100px) for responsiveness.

Metadata

RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free