React Spreadsheet Grid

An Excel-like grid component for React with custom cell editors, performant...

README

React Spreadsheet Grid

An Excel-like grid component for React with custom cell editors, performant scroll & resizable columns


react-spreadsheet-grid in action

The key features


This is an Excel-like Spreadsheet Grid component that supports:

✅  Custom cell editors (use built-in Input and Select, or any other components) & header content

✅  Performant scroll for as many rows as you need

✅  Resizable columns

✅  Control by mouse & from keyboard

✅  Flexible setting of disabled cells

✅  Lazy loading support

✅  Customizable CSS styling

✅  Hooks compatible

✅  TypeScript compatible

Table of contents


-   Props
    -   Built-in Input
    -   Built-in Select
    -   Another component

Live playground


For examples of the grid in action, you can run the demo on your own computer:

Clone this repository
npm install
npm run storybook
Visit http://localhost:6006/

Installation


This module is distributed via npm and should be installed as one of your project'sdependencies:

  1. ```
  2. npm install --save react-spreadsheet-grid
  3. ```

⚠️ IMPORTANT! This package also depends on react, react-dom and prop-types. Please make sure you have those installed as well.


A primitive example


  1. ``` js
  2. import React, { useState } from 'react'
  3. import { Grid, Input, Select } from 'react-spreadsheet-grid'

  4. const rows = [
  5.     { id: 'user1', name: 'John Doe', positionId: 'position1' },
  6.     // and so on...
  7. ];

  8. const MyAwesomeGrid = () => {
  9.   return (
  10.     <Grid
  11.       columns={[
  12.         {
  13.           title: () => 'Name',
  14.           value: (row, { focus }) => {
  15.               return (
  16.                   <Input
  17.                     value={row.name}
  18.                     focus={focus}
  19.                   />
  20.               );
  21.           }
  22.         }, {
  23.           title: () => 'Position',
  24.           value: (row, { focus }) => {
  25.               return (
  26.                   <Select
  27.                     value={row.positionId}
  28.                     isOpen={focus}
  29.                     items={somePositions}
  30.                   />
  31.               );
  32.           }
  33.         }
  34.       ]}
  35.       rows={rows}
  36.       getRowKey={row => row.id}
  37.     />
  38.   )
  39. }
  40. ```

The pattern of regular usage


Take a closer look at 2 main thing: a declaration of columns and work with the state of the parent component.

To get the correct behavior of the grid you should:

Store rows and columns of the grid in the state of the parent component.
Describe how the grid renders values of the cells.
Have a callback that changes values of the rows in the state of the parent component.

Let's see how it works:

  1. ``` js
  2. import { Grid, Input, Select } from 'react-spreadsheet-grid'
  3. import AwesomeAutocomplete from 'awesome-autocomplete'

  4. const rows = [
  5.     { id: 'user1', name: 'John Doe', positionId: 'position1', managerId: 'manager1' },
  6.     // and so on...
  7. ];

  8. const MyAwesomeGrid = () => {
  9.     // Rows are stored in the state.
  10.     const [rows, setRows] = useState(rows);

  11.     // A callback called every time a value changed.
  12.     // Every time it save a new value to the state.
  13.     const onFieldChange = (rowId, field) => (value) => {
  14.         // Find the row that is being changed
  15.         const row = rows.find({ id } => id === rowId);
  16.         
  17.         // Change a value of a field
  18.         row[field] = value;
  19.         setRows([].concat(rows))
  20.     }
  21.     
  22.     const initColumns = () => [
  23.       {
  24.         title: () => 'Name',
  25.         value: (row, { focus }) => {
  26.           // You can use the built-in Input.
  27.           return (
  28.             <Input
  29.               value={row.name}
  30.               focus={focus}
  31.               onChange={onFieldChange(row.id, 'name')}
  32.             />
  33.           );
  34.         }
  35.       }, {
  36.         title: () => 'Position',
  37.         value: (row, { focus }) => {
  38.             // You can use the built-in Select.
  39.             return (
  40.                 <Select
  41.                   value={row.positionId}
  42.                   isOpen={focus}
  43.                   items={somePositions}
  44.                   onChange={onFieldChange(row.id, 'positionId')}
  45.                 />
  46.             );
  47.         }
  48.       }, {
  49.         title: () => 'Manager',
  50.         value: (row, { active, focus }) => {
  51.           // You can use whatever component you want to change a value.
  52.           return (
  53.             <AwesomeAutocomplete
  54.               value={row.managerId}
  55.               active={active}
  56.               focus={focus}
  57.               onSelectItem={onFieldChange(row.id, 'managerId')}
  58.             />
  59.           );
  60.         }
  61.       }
  62.     ]

  63.     return (
  64.         <Grid
  65.             columns={initColumns()}
  66.             rows={rows}
  67.             isColumnsResizable
  68.             onColumnResize={onColumnResize}
  69.             getRowKey={row => row.id}
  70.         />
  71.     )
  72. }
  73. ```

Props


columns


  1. ``` js
  2. arrayOf({
  3.     id: string / number,
  4.     title: string / func,
  5.     value: string / func(row, { active, focus, disabled }),
  6.     width: number,
  7.     getCellClassName: func(row)
  8. })
  9. ```

defaults to []


required


This is the most important prop that defines columns of the table. Every item of the array is responsible for the corresponding column.

key | Required | Mission
id | yes | An identifier of a row.
title | yes | This is what you want to put in the header of the column, it could be passed as a string or as a func returning a React element.
value | yes | This is content of the cell. Works the same way as title, but func receives row and current state of the cell ({ active, focus, disabled }) as parameters, so you can create an output based on them.
width | no | Pass this property if you want to initialize the width of a column. You can set width not for all the columns, then the rest of the table width would be distributed between the columns with unspecified width. Also, you can get width of the columns from onColumnResize callback to store somewhere and use for the next render to make columns stay the same width.
getCellClassName | no | An additional class name getter for a row.

rows

arrayOf(any) | defaults to []


required


This is an array of rows for the table. Every row will be passed to a column.value func (if you use it).

getRowKey

func(row)


required


This is a func that must return unique key for a row based on this row in a parameter.

placeholder

string | defaults to "There are no rows"


Used as a placeholder text when the rows array is empty.

disabledCellChecker

func(row, columnId): bool


Use this func to define what cells are disabled in the table. It gets row and columnId (defined as column.id in a columns array) as parameters and identifiers of a cell. It should return boolean true / false. A disabled cell gets special CSS-class and styles. Also, you can define a column.value output based on the disabled state parameter.

onCellClick

func(row, columnId)


A click handler function for a cell. It gets row and columnId (defined as column.id in the columns array) as parameters and identifiers of a cell.

onActiveCellChanged

func({ x, y })


A callback called every time the active cell is changed. It gets { x, y } coordinates of the new active cell as parameters.

headerHeight

number | defaults to 40


The height of the header of the table in pixels.

⚠️ Define it as a prop, not in CSS styles to not broke the scroll of the table. ⚠️

rowHeight

number | defaults to 48


The height of a row of the table in pixels.

⚠️ Define it as a prop, not in CSS styles to not broke the scroll of the table. ⚠️

focusOnSingleClick

boolean


defaults to false


By default, double clicking a cell sets the focus on the cell's input. Pass true if you want to set the focus on the cell's input upon single clicking it.

isColumnsResizable

bool | defaults to false


Switch this on if you want the table provides an opportunity to resize column width.

onColumnResize

func(widthValues: object)


A callback called every time the width of a column was resized. Gets widthValues object as a parameter. widthValues is a map of values of width for all the columns in percents (columnId - value).

isScrollable

boolean


defaults to true


This defines should a grid has a scrollable container inside of a DOM-element where it was rendered, or not. When it turned on (by default), only visible rows are rendered and that improves performance. If you pass false, all the rows will be rendered at once (that is not a good way to handle with a big amount of them), but you will have opportunity to set up a scroll area where you want it to be and have other components (before or after the grid) included in this area.

onScroll

func(scrollPosition: number)


A callback called every time the position of the scroll of the grid was changed.

onScrollReachesBottom

func()


A callback called when the scroll of the grid reaches its bottom value. Usually, it could be used to implement the lazy loading feature in your grid (see the Lazy loading support section for details).

Public methods


Use public methods via a grid's ref:

  1. ``` js
  2. const GridWrapper = () => {
  3.   const gridRef = React.createRef()

  4.   React.useEffect(() => {
  5.     gridRef.current.resetScroll()
  6.   })

  7.   return (
  8.     <Grid
  9.       ref={gridRef}
  10.       // other props
  11.     />
  12.   )
  13. }
  14. ```

resetScroll()


Call to reset the scroll to the top of the container.

focusCell({ x: number, y: number })


Call to make the cell with this x, y coordinates (starting from 0) active and focused.

Customizing cells & header content


You can customize content of titles and cells using title and value keys of elements of the columns property. Setting these components using row and { active, focus, disabled } parameters of the functions.

title could be a string or a func returning any React element.

value works the same way, but func receives current row and current state of the cell ({ active, focused, disabled }) as parameters, so you can create an output based on them.

For the basic usage, the library provide 2 default components that you can use out-of-the-box: Input and Select. Perhaps, they will be enough for you. However, you can use any other React components for that purpose: autocompletes, checkboxes, etc.

Built-in Input


Input prop types:

Prop | Type | Mission
value | string | The value of the input
placeholder | string | Placeholder displaying when there is no value
focus | bool | Should the input has focus or not
selectTextOnFocus | bool | Should the input content be selected when focused or not
onChange | func | Blur callback. Use it to catch a changed value

Usage:

  1. ``` js
  2. import { Grid, Input } from 'react-spreadsheet-grid'

  3. <Grid
  4.     columns={[
  5.       {
  6.         id: 'name',
  7.         title: () => {
  8.             return <span>Name</span>
  9.         },
  10.         value: (row, { focus }) => {
  11.           return (
  12.             <Input
  13.               value={row.name}
  14.               focus={focus}
  15.               onChange={onFieldChange(row.id, 'name')}
  16.             />
  17.           );
  18.         }
  19.       }
  20.    ]}
  21. />
  22. ```

Built-in Select


Select prop types:

Prop | Type | Mission
items | arrayOf({ id: string / number, name: string }) | Items for select
selectedId | string / number | Id of a selected item
placeholder | string | Placeholder displaying when there is no selected item
isOpen | bool | Should the select be open or not
onChange | func | Change item callback. Use it to catch a changed value

Usage:

  1. ``` js
  2. import { Grid, Select } from 'react-spreadsheet-grid'

  3. const positions = [{
  4.     id: 1,
  5.     name: 'Frontend developer'
  6. }, {
  7.     id: 2,
  8.     name: 'Backend developer'
  9. }];

  10. <Grid
  11.     columns={[
  12.       {
  13.         id: 'position',
  14.         title: () => {
  15.             return <span>Position</span>
  16.         },
  17.         value: (row, { focus }) => {
  18.           return (
  19.             <Select
  20.               items={positions}
  21.               selectedId={row.positionId}
  22.               isOpen={focus}
  23.               onChange={onFieldChange(row.id, 'positionId')}
  24.             />
  25.           );
  26.         }
  27.       }
  28.    ]}
  29. />
  30. ```

Another component


Let's suggest you need to use an autocomplete as a content of a cell. This is how it could be done:

  1. ``` js
  2. import { Grid } from 'react-spreadsheet-grid'
  3. import AwesomeAutocomplete from 'awesome-autocomplete'

  4. <Grid
  5.   columns={[
  6.     {
  7.       id: 'manager',
  8.       title: () => {
  9.         return <span>Manager</span>
  10.       },
  11.       value: (row, { focus, active }) => {
  12.         return (
  13.           <AwesomeAutocomplete
  14.             value={row.managerId}
  15.             active={active}
  16.             focus={focus}
  17.             onSelectItem={onFieldChange(row.id, 'managerId')}
  18.           />
  19.         );
  20.       }
  21.     }
  22.   ]}
  23. />
  24. ```

Performant scroll


A behavior of scroll depends on the isScrollable prop.

If isScrollable is false, the grid renders all the passed rows without a scroll. Probably, this would be useful for small amount of the rows.

If isScrollable is true, the height of the grid is equal to the height of its container, it has a scroll and renders only the rows that are visible. Therefore, you can pass to it as many rows as you want - it will work fine without any problems with rendering and scroll. This would be useful for big amount of the rows.

This is an example, how we could make a 500px height scrollable grid:

  1. ``` js
  2. <div style={{ height: '500px' }}>
  3.     <Grid
  4.         isScrollable
  5.         /* other props */
  6.     />
  7. </div>
  8. ```

Resizable columns


react-spreadsheet-grid provides the opportunity to set initial width values for columns, to resize them from the UI and to react on these changes. Use relevant columnWidthValues, isColumnsResizable and onColumnResize properties for that purpose.

This is how it could be done:

  1. ``` js
  2. import React, { useState } from 'react'
  3. import { Grid } from 'react-spreadsheet-grid'

  4. const ResizableGrid = () => {
  5.     // Put columns to the state to be able to store there their width values.
  6.     const [columns, setColumns] = useState(initColumns())

  7.     // Change columns width values in the state to not lose them.
  8.     const onColumnResize = (widthValues) => {
  9.         const newColumns = [].concat(columns)
  10.         Object.keys(widthValues).forEach((columnId) => {
  11.             newColumns[columnId].width = widthValues[columnId]
  12.         })
  13.         setColumns(newColumns)
  14.     }

  15.     return (
  16.         <Grid
  17.             columns={columns}
  18.             isColumnsResizable
  19.             onColumnResize={onColumnResize}
  20.             rows={/* some rows here */}
  21.             getRowKey={row => row.id}
  22.         />
  23.     )
  24. }
  25. ```

Control by mouse & from keyboard


react-spreadsheet-grid could be controlled by a mouse and from keyboard (just like Excel-table could). When a mouse is used, single click make a cell active, double click make a cell focused. When a keyboard used, move active cell, ENTER and TAB make a cell focused.

Customizing CSS styles


Right now, the easiest way to tweak react-spreadsheet-grid is to create another stylesheet to override the default styles. For example, you could create a file named react_spreadsheet_grid_overrides.css with the following contents:

  1. ```css
  2. .SpreadsheetGrid__cell_active {
  3.     box-shadow: inset 0 0 0 2px green;
  4. }
  5. ```

This would override the color of borders for the table active cell.

⚠️ The only exception, that you have to use headerHeight and rowHeight props to redefine height of the header and rows to not broke the scroll of the table.

Lazy loading support


react-spreadsheet-grid provides the opportunity to implement the lazy loading feature in your grid. Use the onScrollReachesBottom callback to handle a situation when the scroll position reaches its bottom. Load a new portion of the rows and put them in the state of a high-order component.

This is how it could be done:

  1. ``` js
  2. import React, { useState } from 'react'
  3. import { Grid } from 'react-spreadsheet-grid'

  4. const LazyLoadingGrid = () => {
  5.   /* Init the state with the initial portion of the rows */
  6.   const [rows, setRows] = useState(initialRows);

  7.   const onScrollReachesBottom = () => {
  8.      loadNewPortionOfRows().then((newRows) => {
  9.         setRows(rows.concat(newRows));
  10.      });
  11.   }

  12.   const loadNewPortionOfRows = () => {
  13.     /* an ajax request here */
  14.   }

  15.   return (
  16.       <Grid
  17.         columns={/* some columns here */}
  18.         row={rows}
  19.         getRowKey={row => row.id}
  20.         onScrollReachesBottom={onScrollReachesBottom}
  21.       />
  22.     )
  23. }
  24. ```