### Install React-Datasheet using npm Source: https://github.com/nadbm/react-datasheet/blob/master/README.md This command installs the react-datasheet package from npm. It's a necessary first step before importing and using the component in a React project. ```bash npm install react-datasheet --save ``` -------------------------------- ### React-Datasheet with custom data rendering Source: https://github.com/nadbm/react-datasheet/blob/master/README.md This JSX example demonstrates how to use `valueRenderer` and `dataRenderer` to display different representations of cell data. It formats dates for display and uses ISO strings when editing, based on the column index. ```jsx const grid = [ [{value: 5, expr: '1 + 4'}, {value: 6, expr: '6'}, {value: new Date('2008-04-10')}], [{value: 5, expr: '1 + 4'}, {value: 5, expr: '1 + 4'}, {value: new Date('2004-05-28')}] ] const onCellsChanged = (changes) => changes.forEach(({cell, row, col, value}) => console.log("New expression :" + value)) j == 2 ? cell.value.toDateString() : cell.value} dataRenderer={(cell, i, j) => j == 2 ? cell.value.toISOString() : cell.expr} onCellsChanged={onCellsChanged} /> ``` -------------------------------- ### TypeScript Basic Usage with React DataSheet Source: https://github.com/nadbm/react-datasheet/blob/master/USAGE_TYPESCRIPT.md This example shows basic integration of React DataSheet with TypeScript. It defines a custom GridElement type for cells, a custom cell renderer, and implements data handling for cell changes. It requires the 'react-datasheet' library. ```tsx import * as React from 'react'; import ReactDataSheet from 'react-datasheet'; import "react-datasheet/lib/react-datasheet.css"; export interface GridElement extends ReactDataSheet.Cell { value: number | null; } class MyReactDataSheet extends ReactDataSheet { } interface AppState { grid: GridElement[][]; } //You can also strongly type all the Components or SFCs that you pass into ReactDataSheet. let cellRenderer: ReactDataSheet.CellRenderer = (props) => { const backgroundStyle = props.cell.value && props.cell.value < 0 ? {color: 'red'} : undefined; return ( {props.children} ) } export class App extends React.Component<{}, AppState> { constructor (props: {}) { super(props) this.state = { grid: [ [{value: 1}, {value: -3}], [{value: -2}, {value: 4}] ] } } render () { return ( cell.value} onCellsChanged={changes => { const grid = this.state.grid.map(row => [...row]) changes.forEach(({cell, row, col, value}) => { grid[row][col] = {...grid[row][col], value} }) this.setState({grid}) }} cellRenderer={cellRenderer} /> ) } } ``` -------------------------------- ### React-DataSheet Selection and Selection Change Handler Source: https://github.com/nadbm/react-datasheet/blob/master/README.md This snippet demonstrates how to control and react to cell selections in React-DataSheet. The `selected` prop allows for controlled selection management, while the `onSelect` handler is triggered whenever the selection changes, providing the start and end coordinates of the selection. ```javascript import React from 'react'; import DataSheet from 'react-datasheet'; class SelectableSheet extends React.Component { state = { grid: [ [{ value: 'A1' }, { value: 'B1' }], [{ value: 'A2' }, { value: 'B2' }] ], selection: { start: { i: 0, j: 0 }, end: { i: 0, j: 0 } } }; handleSelect = ({ start, end }) => { console.log('Selection changed:', { start, end }); this.setState({ selection: { start, end } }); }; render() { return ( ); } } export default SelectableSheet; ``` -------------------------------- ### React-Datasheet with custom cell attributes Source: https://github.com/nadbm/react-datasheet/blob/master/README.md This JSX example illustrates how to add custom HTML attributes to cells using the `attributesRenderer` prop. This is useful for applying ARIA attributes, data attributes for styling, or other metadata to individual cells. ```jsx const grid = [ [{value: 1, hint: 'Valid'}, {value: 3, hint: 'Not valid'}], [{value: 2}, {value: 4}] ] cell.value} attributesRenderer={(cell) => (cell.hint ? { 'data-hint': cell.hint } : {})} ... /> ``` -------------------------------- ### Customizing React-Datasheet with Row and Cell Renderers Source: https://github.com/nadbm/react-datasheet/blob/master/README.md This example demonstrates how to implement custom renderers for the sheet, rows, value viewers, and data editors in React-Datasheet. It allows for structural changes like adding headers and row selection checkboxes, as well as custom cell editing and viewing logic. Dependencies include React and React-Datasheet. Inputs are the grid data and selection state; outputs are the customized grid interface. Performance considerations suggest using bound functions or separate components for renderers to avoid re-renders. ```jsx const columns = getColumnsFromSomewhere() const isSelected = yourSelectionFunction const selectHandler = yourCallbackFunction cell.value} sheetRenderer={props => ( ))} {props.children}
{columns.map(col => ({col.name}
)} rowRenderer={props => ( {props.children} )} valueViewer={MyViewComponent} dataEditor={props => ( props.col === 0 ? : )} ... /> ``` -------------------------------- ### Import React-Datasheet and its CSS Source: https://github.com/nadbm/react-datasheet/blob/master/README.md This Javascript code snippet demonstrates how to import the React-Datasheet component and its associated CSS file into a React project. Importing the CSS is crucial for the component to render correctly. ```javascript import ReactDataSheet from 'react-datasheet'; // Be sure to include styles at some point, probably during your bootstrapping import 'react-datasheet/lib/react-datasheet.css'; ``` -------------------------------- ### Basic React-Datasheet Usage Source: https://github.com/nadbm/react-datasheet/blob/master/README.md This JSX code shows a basic implementation of React-Datasheet within a React component. It initializes a grid state and passes it to the ReactDataSheet component, along with a valueRenderer and an onCellsChanged callback to handle data updates. ```jsx class App extends React.Component { constructor(props) { super(props); this.state = { grid: [ [{ value: 1 }, { value: 3 }], [{ value: 2 }, { value: 4 }], ], }; } render() { return ( cell.value} onCellsChanged={changes => { const grid = this.state.grid.map(row => [...row]); changes.forEach(({ cell, row, col, value }) => { grid[row][col] = { ...grid[row][col], value }; }); this.setState({ grid }); }} /> ); } } ``` -------------------------------- ### Advanced Options Source: https://github.com/nadbm/react-datasheet/blob/master/README.md Customization options for overriding default renderers and editors in react-datasheet. ```APIDOC ## Advanced Options ### Description These are optional functions or React Components that can completely override the native renderers of react-datasheet. ### Options - **sheetRenderer** (func) - Optional function or React Component to render the main sheet element. The default renders a `table` element. - **rowRenderer** (func) - Optional function or React Component to render each row element. The default renders a `tr` element. - **cellRenderer** (func) - Optional function or React Component to render each cell element. The default renders a `td` 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. - **dataEditor** (func) - Optional function or React Component to render a custom editor. Affects every cell in the sheet. - **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 } }`, or `null` for no selection. - **onSelect** (func) - Optional. `function ({ start, end }) {}` Triggered on every selection change. `start` and `end` have the same format as the `selected` prop. ### Further Information See [custom renderers](https://github.com/nadbm/react-datasheet#custom-renderers-1) and [cell options](https://github.com/nadbm/react-datasheet#cell-options) for more details. ``` -------------------------------- ### Data Editor Component Contract for React-DataSheet Source: https://github.com/nadbm/react-datasheet/blob/master/README.md Custom data editors in React-DataSheet must adhere to a specific contract by accepting and utilizing certain props. These props enable the editor to manage data, respond to user input, and communicate editing status back to the grid. Key props include `value`, `row`, `col`, `cell`, `onChange`, `onKeyDown`, `onCommit`, and `onRevert`. ```javascript function MyCustomEditor(props) { // 'value' is the current cell value // 'onChange' is a function to call when the value changes // 'onCommit' is a function to call when editing is finished // 'onRevert' is a function to call when editing is cancelled // 'onKeyDown' is a function to call for key events // 'row' and 'col' are the cell's coordinates // 'cell' is the cell's data object const handleChange = (event) => { props.onChange(event.target.value); }; const handleKeyDown = (event) => { // Example: trigger default handling for Enter/Escape props.onKeyDown(event); }; const handleCommit = () => { // Assume 'newValue' is the final value from the editor props.onCommit(newValue); }; const handleRevert = () => { props.onRevert(); }; return ( ); } ``` -------------------------------- ### React-DataSheet Custom Renderers and Editors Source: https://github.com/nadbm/react-datasheet/blob/master/README.md This snippet illustrates the usage of advanced options in React-DataSheet for customizing the rendering and editing behavior of the grid. These options allow developers to override default behaviors for the entire sheet, rows, cells, value display, and data editing, providing a high degree of flexibility. ```javascript import React from 'react'; import DataSheet from 'react-datasheet'; class MySheet extends React.Component { state = { grid: [ [{ value: 'Value 1' }, { value: 'Value 2' }], [{ value: 'Value 3' }, { value: 'Value 4' }] ] }; // Custom cell renderer cellRenderer = ({ cell, row, col, editing, onMouseDown, onDoubleClick, ...props }) => ( {cell.value} ); // Custom data editor dataEditor = ({ value, onCommit, onKey, ...props }) => ( onCommit(e.target.value)} onKeyDown={onKey} {...props} /> ); render() { return ( ); } } export default MySheet; ``` -------------------------------- ### onCellsChanged Handler Source: https://github.com/nadbm/react-datasheet/blob/master/README.md Callback function invoked when data in the grid changes. ```APIDOC ## `onCellsChanged(arrayOfChanges[, arrayOfAdditions])` Handler ### Description React-DataSheet calls this callback whenever data in the grid changes, such as when a user edits a cell, deletes selected cells, or pastes data. ### Parameters - **arrayOfChanges** (array) - An array of objects, where each object represents a change and has the following properties: - **cell** (object | null) - The original cell object provided in the `data` property, or `null`. - **row** (number) - The row index of the changed cell. - **col** (number) - The column index of the changed cell. - **value** (any) - The new cell value. - **arrayOfAdditions** (array, optional) - An array of objects representing out-of-bounds data when pasting. These objects have `row`, `col`, and `value` properties, but no `cell` property. ### Usage Scenarios - User enters a new value in a cell. - User hits the delete key with one or more selected cells. - User pastes tabular data into the table. ### Handling Additions The `arrayOfAdditions` argument allows you to manage data pasted beyond the grid's current bounds, either by ignoring it or expanding your data model. ``` -------------------------------- ### React-DataSheet onCellsChanged Handler for Data Modifications Source: https://github.com/nadbm/react-datasheet/blob/master/README.md This snippet shows how to implement the `onCellsChanged` handler in React-DataSheet. This function is called whenever data in the grid is modified, whether by direct user input, deletion, or pasting. It receives an array of change objects detailing the modifications. ```javascript import React from 'react'; import DataSheet from 'react-datasheet'; class EditableSheet extends React.Component { state = { grid: [ [{ value: 'Initial Value 1' }, { value: 'Initial Value 2' }], [{ value: 'Initial Value 3' }, { value: 'Initial Value 4' }] ] }; handleCellsChanged = (changes, additions) => { console.log('Changes:', changes); if (additions && additions.length > 0) { console.log('Additions:', additions); // Logic to handle new rows/columns from pasting data outside bounds } // Update the grid state based on changes const grid = this.state.grid.map(row => row.map(cell => { const matchingChange = changes.find(c => c.row === this.state.grid.indexOf(row) && c.col === row.indexOf(cell)); return matchingChange ? { ...cell, value: matchingChange.value } : cell; }) ); this.setState({ grid }); }; render() { return ( ); } } export default EditableSheet; ``` -------------------------------- ### Deprecated onChange Handler for React-DataSheet Source: https://github.com/nadbm/react-datasheet/blob/master/README.md The 'onChange' handler is a deprecated function that previously supported direct cell updates. It is called with the cell details, row and column indices, and the new value. While still functional for backward compatibility, it is scheduled for removal. ```javascript function(cell, i, j, newValue) {} ``` -------------------------------- ### React-Datasheet with component in cells Source: https://github.com/nadbm/react-datasheet/blob/master/README.md This JSX snippet shows how to embed custom React components within cells of the React-Datasheet. The `component` property on a cell object allows for interactive elements like buttons to be rendered within the spreadsheet. ```jsx const grid = [ [{ value: 5, component: ( ) }] ] cell.value} /> ``` -------------------------------- ### Deprecated onPaste Handler for React-DataSheet Source: https://github.com/nadbm/react-datasheet/blob/master/README.md The 'onPaste' handler is a deprecated function used for handling pasted data. It receives an array of rows, where each row contains cell objects and their raw pasted values. If a pasted value doesn't match a cell, its value will be undefined. This handler is maintained for backward compatibility. ```javascript function(array) {} ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.