- Notifications
You must be signed in to change notification settings - Fork452
Excel-like data grid (table) component for React
License
nadbm/react-datasheet
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
react-datasheet is no longer under active development. New maintainers are wanted. Please contact me if you wish to maintain this repo.
A simple react component to create a spreadsheet.
Demo here:https://nadbm.github.io/react-datasheet/
Examples are located inhttps://github.com/nadbm/react-datasheet/tree/master/docs/src/examples
Current features:
- Select cells, cut, copy and paste cells
- Navigation using keyboard keys
- Deletion using keyboard keys
- Callbacks for onCellsChanged, valueRenderer(visible data)
- dataRenderer(underlying data in the input, takes the value by default)
- Supply your own editors and view controls with custom renderers
- Extensive control over generated markup via custom renderers
Using Typescript?View Usage
Install from npm:
$ npm install react-datasheet --save
Import in your project:
importReactDataSheetfrom'react-datasheet';// Be sure to include styles at some point, probably during your bootstrappingimport'react-datasheet/lib/react-datasheet.css';
React-Datasheet generates a table with the cells. Double-clicking or typingedits the value and if changed, initiates anonCellsChanged callback. Pastingtabular data or deleting a range of cells also callsonCellsChanged.
The data provided should be an array of rows, and each row should include thecells.
classAppextendsReact.Component{constructor(props){super(props);this.state={grid:[[{value:1},{value:3}],[{value:2},{value:4}],],};}render(){return(<ReactDataSheetdata={this.state.grid}valueRenderer={cell=>cell.value}onCellsChanged={changes=>{constgrid=this.state.grid.map(row=>[...row]);changes.forEach(({ cell, row, col, value})=>{grid[row][col]={ ...grid[row][col], value};});this.setState({ grid});}}/>);}}
There are two values that each cell shows. The first is viavalueRenderer andthe second is viadataRenderer. When a cell is inedit mode, it will showthe value returned fromdataRenderer. It needs to return a string as thisvalue is set in an input field. Each of these callbacks are passed the cellvalue as well as the cell's coordinates in the spreadsheet. This allows you toapply formatting logic at rendering time, such asall cells in the third columnshould be formatted as dates.
constgrid=[[{value:5,expr:'1 + 4'},{value:6,expr:'6'},{value:newDate('2008-04-10')}],[{value:5,expr:'1 + 4'},{value:5,expr:'1 + 4'},{value:newDate('2004-05-28')}]]constonCellsChanged=(changes)=>changes.forEach(({cell, row, col, value})=>console.log("New expression :"+value))<ReactDataSheetdata={grid}valueRenderer={(cell,i,j)=>j==2 ?cell.value.toDateString() :cell.value}dataRenderer={(cell,i,j)=>j==2 ?cell.value.toISOString() :cell.expr}onCellsChanged={onCellsChanged}/>
constgrid=[[{value:5,component:(<buttononClick={()=>console.log("clicked")}> Rendered</button>)}]]<ReactDataSheetdata={grid}valueRenderer={(cell)=>cell.value}/>
This renders a single cell with the value 5. Once in edit mode, the button willappear.
constgrid=[[{value:1,hint:'Valid'},{value:3,hint:'Not valid'}],[{value:2},{value:4}]]<ReactDataSheetdata={grid}valueRenderer={(cell)=>cell.value}attributesRenderer={(cell)=>(cell.hint ?{'data-hint':cell.hint} :{})} .../>
This render 2 rows, each one with two cells, the cells in the first row willhave an attribute data-hint and the other 2 will not.
React-Datasheet allows you replace the renderers both for the overall structure(rows, cells, the sheet itself) as well as editors and viewers for individualcells. This allows you to radically refashion the sheet to suit yourrequirements.
For example, this shows how to add separate headers and a checkbox at the startof each row to control row "selected" state. It also specifies a custom viewrenderer and a custom editor for the first column of each row:
constcolumns=getColumnsFromSomewhere()constisSelected=yourSelectionFunctionconstselectHandler=yourCallbackFunction<ReactDataSheetdata={grid}valueRenderer={(cell)=>cell.value}sheetRenderer={props=>(<tableclassName={props.className+' my-awesome-extra-class'}><thead><tr><thclassName='action-cell'/>{columns.map(col=>(<th>{col.name}</th>))}</tr></thead><tbody>{props.children}</tbody></table>)}rowRenderer={props=>(<tr><tdclassName='action-cell'><inputtype='checkbox'checked={isSelected(props.row)}onChange={selectHandler}/></td>{props.children}</tr>)}valueViewer={MyViewComponent}dataEditor={props=>(props.col===0 ?<MyDatePicker{...props}/> :<DataEditor{...props}/>)} .../>
Note: For brevity, in this example the custom renderers are all defined asarrow functions inside of render, but using abound function in the parentcomponent or a separate custom component will let you avoid a lot of needlessre-renders.
| Option | Type | Description |
|---|---|---|
| data | Array | Array of rows and each row should contain the cell objects to display |
| valueRenderer | func | Method to render the value of the cellfunction(cell, i, j). This is visible by default |
| dataRenderer | func | Method to render the underlying value of the cellfunction(cell, i, j). This data is visible once in edit mode. |
| overflow | 'wrap'|'nowrap'|'clip' | Grid default for how to render overflow text in cells |
| onCellsChanged | func | onCellsChanged handler:function(arrayOfChanges[, arrayOfAdditions]) {}, where changes is anarray of objects of the shape{cell, row, col, value}. See below for more details. |
| onContextMenu | func | Context menu handler :function(event, cell, i, j) |
| parsePaste | func | function (string) {} If set, the function will be called with the raw clipboard data. It should return an array of arrays of strings. This is useful for when the clipboard may have data with irregular field or line delimiters. If not set, rows will be split with line breaks and cells with tabs. |
| isCellNavigable | func | function (cell, row, col) {return true} If set, the function is used to determine whether navigation to the indicated cell should be allowed or not. If not then using cursor or tab navigation will skip over not allowed cells until it finds the next allowed cell. |
| handleCopy | func | function ({ event, dataRenderer, valueRenderer, data, start, end, range }) If set, this function is called whenever the user copies cells. The return string of this function is stored on the clipboard. |
The following are optional functions or React Component that can completelyoverride the native renderers of react datasheet. To know which props are passeddown, seecustom renderers
| Option | Type | Description |
|---|---|---|
| sheetRenderer | func | Optional function or React Component to render the main sheet element. The default renders atable element. |
| rowRenderer | func | Optional function or React Component to render each row element. The default renders atr element. |
| cellRenderer | func | Optional function or React Component to render each cell element. The default renders atd element. |
| valueViewer | func | Optional function or React Component to customize the way the value for each cell in the sheet is displayed. Affects every cell in the sheet. Seecell options to override individual cells. |
| dataEditor | func | Optional function or React Component to render a custom editor. Affects every cell in the sheet. Seecell options to override individual cells. |
| selected | object | Optional. Whether the selection is controlled or uncontrolled. Must be an object of this format:{ start: { i: number, j; number }, end: { i: number, j: number } }, ornull for no selection. |
| onSelect | func | Optional.function ({ start, end }) {} Triggered on every selection change.start andend have the same format as theselected prop. |
React-DataSheet will call this callback whenever data in the grid changes:
- When the user enters a new value in a cell
- When the user hits the delete key with one or more selected cells
- When the user pastes tabular data into the table
The argument to the callback usually will be onearray of objects with theseproperties:
| Property | Type | Description |
|---|---|---|
| cell | object | the original cell object you provided in thedata property. This may benull (see below) |
| row | number | row index of changed cell |
| col | number | column index of changed cell |
| value | any | The new cell value. This is usually a string, but a custom editor may provide any type of value. |
If the change is the result of a user edit, the array will contain a singlechange object. If the user pastes data or deletes a range of cells, the arraywill contain an element for each affected cell.
Additions: If the user pastes data that extends beyond the bounds of thegrid (for example, pasting two-row-high data on the last line), there will be asecond argument to the handler containing an array of objects that represent theout-of-bounds data. These object will have the same properties, except:
- There is no
cellproperty - either
roworcol, or both, will be outside the bounds of your originalgrid. They will correspond to the indices the new data would occupy if youexpanded your grid to hold them.
You can choose to ignore the additions, or you can expand your model toaccommodate the new data.
Previously React-DataSheet supported two change handlers. These are stillsupported for backwards compatibility, but will be removed at some point in thefuture.
| Option | Type | Description |
|---|---|---|
| onChange | func | onChange handler:function(cell, i, j, newValue) {} |
| onPaste | func | onPaste handler:function(array) {} If set, the function will be called with an array of rows. Each row has an array of objects containing the cell and raw pasted value. If the pasted value cannot be matched with a cell, the cell value will be undefined. |
The cell object is what gets passed back to the onChange callback. They cancontain the following options as well
| Option | Type | Default | Description |
|---|---|---|---|
| readOnly | Bool | false | Cell will never go in edit mode |
| key | String | undefined | By default, each cell is given the key of col number and row number. This would override that key |
| className | String | undefined | Additional class names for cells. |
| component | ReactElement | undefined | Insert a react element or JSX to this field. This will render on edit mode |
| forceComponent | bool | false | Renders what's in component at all times, even when not in edit mode |
| disableEvents | bool | false | Makes cell unselectable and read only |
| colSpan | number | 1 | The colSpan of the cell's td element |
| rowSpan | number | 1 | The rowSpan of the cell's td element |
| width | number or String | undefined | Sets the cell's td width using a style attribute. Number is interpreted as pixels, strings are used as-is. Note: This will only work if the table does not have a set width. |
| overflow | 'wrap'|'nowrap'| 'clip' | undefined | How to render overflow text. Overrides grid-leveloverflow option. |
| valueViewer | func | undefined | Optional function or React Component to customize the way the value for this cell is displayed. Overrides grid-levelvalueViewer option. |
| dataEditor | func | undefined | Optional function or React Component to render a custom editor. Overrides grid-leveldataEditor option. |
Each of the following custom renderers should be either a React Component or afunction that takes aprops argument and returns a react element (a.k.astateless functional component). React-DataSheet will supply certain propertiesto each renderer.
In some cases React-DataSheet will include event handlers as properties to yourcustom renderer. You must hook up these handlers to your component or aspects ofReact-DataSheet's built-in behavior will cease to work.
Except forvalueViewer anddataEditor, each custom renderer will receivereact's regularprops.children. Be sure to render{props.children} in yourcustom renderer.
ThesheetRenderer is responsible for laying out the sheet's main parentcomponent. By default, React-DataSheet uses atable element. React-DataSheetwill supply these properties:
| Option | Type | Description |
|---|---|---|
| data | Array | The samedata array as from mainReactDataSheet component |
| className | String | Classes to apply to your top-level element. You can add to these, but your should not overwrite or omit them unless you want to implement your own CSS also. |
| children | Array or component | The regular reactprops.children. You must render{props.children} within your custom renderer or you won't see your rows and cells. |
TherowRenderer lays out each row in the sheet. By default, React-DataSheetuses atr element. React-DataSheet will supply these properties:
| Option | Type | Description |
|---|---|---|
| row | number | The current row index |
| selected | Bool | true in case the current row is selected |
| cells | Array | The cells in the current row |
| children | Array or component | The regular reactprops.children. You must render{props.children} within your custom renderer or you won't see your cells. |
ThecellRenderer creates the container for each cell in the sheet. The defaultrenders atd element. React-DataSheet will supply these properties:
| Option | Type | Description |
|---|---|---|
| row | number | The current row index |
| col | number | The current column index |
| cell | Object | The cell's raw data structure |
| className | String | Classes to apply to your cell element. You can add to these, but your should not overwrite or omit them unless you want to implement your own CSS also. |
| style | Object | Generated styles that you should apply to your cell element. This may be null or undefined. |
| selected | Bool | Is the cell currently selected |
| editing | Bool | Is the cell currently being edited |
| updated | Bool | Was the cell recently updated |
| attributesRenderer | func | As for the mainReactDataSheet component |
| onMouseDown | func | Event handler important for cell selection behavior |
| onMouseOver | func | Event handler important for cell selection behavior |
| onDoubleClick | func | Event handler important for editing |
| onContextMenu | func | Event handler to launch default content-menu handling. You can safely ignore this handler if you want to provide your own content menu handling. |
| children | Array or component | The regular reactprops.children. You must render{props.children} within your custom renderer or you won't your cell's data. |
ThevalueViewer displays your cell's data with a custom component when in viewmode. For example, you might show a "three star rating" component instead thenumber 3. You can specify avalueViewer for the entire sheet and/or for anindividual cell.
React-DataSheet will supply these properties:
| Option | Type | Description |
|---|---|---|
| value | node | The result of thevalueRenderer function |
| row | number | The current row index |
| col | number | The current column index |
| cell | Object | The cell's raw data structure |
ThedataEditor displays your cell's data when in edit mode. You can can useany component you want, as long as you hook up the event handlers thatconstitute the contract between React-DataSheet and your editor. You can specifyadataEditor for the entire sheet and/or for an individual cell.
| Option | Type | Description |
|---|---|---|
| value | String or node | The result of thedataRenderer (orvalueRenderer if none) |
| row | number | The current row index |
| col | number | The current column index |
| cell | Object | The cell's raw data structure |
| onChange | func | function (string) {} callback for when the user changes the value during editing (for example, each time they type a character into aninput).onChange does not indicate thefinal edited value. It works just like acontrolled component in a form. |
| onKeyDown | func | function (event) {} An event handler that you can call to use default React-DataSheet keyboard handling to signal reverting an ongoing edit (Escape key) or completing an edit (Enter or Tab). For most editors based on aninput element this will probably work. However, if this keyboard handling is unsuitable for your editor you can trigger these changes explicitly using theonCommit andonRevert callbacks. |
| onCommit | func | function (newValue, [event]) {} A callback to indicate that editing is over, here is the final value. If you pass aKeyboardEvent as the second argument, React-DataSheet will perform default navigation for you (for example, going down to the next row if you hit the enter key). You actually don't need to useonCommit if the default keyboard handling is good enough for you. |
| onRevert | func | function () {} A no-args callback that you can use to indicate that you want to cancel ongoing edits. As withonCommit, you don't need to worry about this if the default keyboard handling works for your editor. |
About
Excel-like data grid (table) component for React
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.