Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Excel-like data grid (table) component for React

License

NotificationsYou must be signed in to change notification settings

nadbm/react-datasheet

Repository files navigation


Build StatusCoverage StatusIssue Countnpm version

React-Datasheet

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

Installation

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';

Usage

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.

Basic Usage

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});}}/>);}}

Cells with underlying data

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}/>

Cells with underlying component

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.

Cells with extra attributes

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.

Custom renderers

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.

Options

OptionTypeDescription
dataArrayArray of rows and each row should contain the cell objects to display
valueRendererfuncMethod to render the value of the cellfunction(cell, i, j). This is visible by default
dataRendererfuncMethod 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
onCellsChangedfunconCellsChanged handler:function(arrayOfChanges[, arrayOfAdditions]) {}, where changes is anarray of objects of the shape{cell, row, col, value}. See below for more details.
onContextMenufuncContext menu handler :function(event, cell, i, j)
parsePastefuncfunction (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.
isCellNavigablefuncfunction (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.
handleCopyfuncfunction ({ 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.

Advanced options

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

OptionTypeDescription
sheetRendererfuncOptional function or React Component to render the main sheet element. The default renders atable element.
rowRendererfuncOptional function or React Component to render each row element. The default renders atr element.
cellRendererfuncOptional function or React Component to render each cell element. The default renders atd element.
valueViewerfuncOptional 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.
dataEditorfuncOptional function or React Component to render a custom editor. Affects every cell in the sheet. Seecell options to override individual cells.
selectedobjectOptional. 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.
onSelectfuncOptional.function ({ start, end }) {} Triggered on every selection change.start andend have the same format as theselected prop.

onCellsChanged(arrayOfChanges[, arrayOfAdditions]) handler

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:

PropertyTypeDescription
cellobjectthe original cell object you provided in thedata property. This may benull (see below)
rownumberrow index of changed cell
colnumbercolumn index of changed cell
valueanyThe 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 nocell property
  • eitherrow orcol, 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.

Deprecated handlers

Previously React-DataSheet supported two change handlers. These are stillsupported for backwards compatibility, but will be removed at some point in thefuture.

OptionTypeDescription
onChangefunconChange handler:function(cell, i, j, newValue) {}
onPastefunconPaste 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.

Cell Options

The cell object is what gets passed back to the onChange callback. They cancontain the following options as well

OptionTypeDefaultDescription
readOnlyBoolfalseCell will never go in edit mode
keyStringundefinedBy default, each cell is given the key of col number and row number. This would override that key
classNameStringundefinedAdditional class names for cells.
componentReactElementundefinedInsert a react element or JSX to this field. This will render on edit mode
forceComponentboolfalseRenders what's in component at all times, even when not in edit mode
disableEventsboolfalseMakes cell unselectable and read only
colSpannumber1The colSpan of the cell's td element
rowSpannumber1The rowSpan of the cell's td element
widthnumber or StringundefinedSets 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'undefinedHow to render overflow text. Overrides grid-leveloverflow option.
valueViewerfuncundefinedOptional function or React Component to customize the way the value for this cell is displayed. Overrides grid-levelvalueViewer option.
dataEditorfuncundefinedOptional function or React Component to render a custom editor. Overrides grid-leveldataEditor option.

Custom Renderers

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.

Sheet Renderer

ThesheetRenderer is responsible for laying out the sheet's main parentcomponent. By default, React-DataSheet uses atable element. React-DataSheetwill supply these properties:

OptionTypeDescription
dataArrayThe samedata array as from mainReactDataSheet component
classNameStringClasses 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.
childrenArray or componentThe regular reactprops.children. You must render{props.children} within your custom renderer or you won't see your rows and cells.

Row Renderer

TherowRenderer lays out each row in the sheet. By default, React-DataSheetuses atr element. React-DataSheet will supply these properties:

OptionTypeDescription
rownumberThe current row index
selectedBooltrue in case the current row is selected
cellsArrayThe cells in the current row
childrenArray or componentThe regular reactprops.children. You must render{props.children} within your custom renderer or you won't see your cells.

Cell Renderer

ThecellRenderer creates the container for each cell in the sheet. The defaultrenders atd element. React-DataSheet will supply these properties:

OptionTypeDescription
rownumberThe current row index
colnumberThe current column index
cellObjectThe cell's raw data structure
classNameStringClasses 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.
styleObjectGenerated styles that you should apply to your cell element. This may be null or undefined.
selectedBoolIs the cell currently selected
editingBoolIs the cell currently being edited
updatedBoolWas the cell recently updated
attributesRendererfuncAs for the mainReactDataSheet component
onMouseDownfuncEvent handler important for cell selection behavior
onMouseOverfuncEvent handler important for cell selection behavior
onDoubleClickfuncEvent handler important for editing
onContextMenufuncEvent handler to launch default content-menu handling. You can safely ignore this handler if you want to provide your own content menu handling.
childrenArray or componentThe regular reactprops.children. You must render{props.children} within your custom renderer or you won't your cell's data.

Value Viewer

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:

OptionTypeDescription
valuenodeThe result of thevalueRenderer function
rownumberThe current row index
colnumberThe current column index
cellObjectThe cell's raw data structure

Data Editor

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.

OptionTypeDescription
valueString or nodeThe result of thedataRenderer (orvalueRenderer if none)
rownumberThe current row index
colnumberThe current column index
cellObjectThe cell's raw data structure
onChangefuncfunction (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.
onKeyDownfuncfunction (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.
onCommitfuncfunction (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.
onRevertfuncfunction () {} 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

Stars

Watchers

Forks

Packages

No packages published

Contributors37


[8]ページ先頭

©2009-2025 Movatter.jp