Integration with Redux
In this tutorial, you will connect Handsontable DataGrid to a Redux store. You will learn to dispatch actions on cell changes and sync grid data with global state.
Integrate with Redux
The following example implements the @handsontable/react-wrapper component with a readOnly toggle switch and the Redux state manager.
Simple example
import { useRef } from 'react';import { createStore } from 'redux';import { Provider, useSelector, useDispatch } from 'react-redux';import { HotTable } from '@handsontable/react-wrapper';import { registerAllModules } from 'handsontable/registry';
// register Handsontable's modulesregisterAllModules();
const ExampleComponentContent = () => { const hotSettings = useSelector((state) => state); const dispatch = useDispatch(); const hotTableComponentRef = useRef(null);
const hotData = hotSettings.data; const isHotData = Array.isArray(hotData);
const onBeforeHotChange = (changes) => { dispatch({ type: 'updateData', dataChanges: changes, });
return false; };
const toggleReadOnly = (event) => { dispatch({ type: 'updateReadOnly', readOnly: event.target.checked, }); };
return ( <div className="dump-example-container"> <div id="example-container"> <div id="example-preview"> <div className="example-controls-container"> <div className="controls"> <label> <input onClick={toggleReadOnly} type="checkbox" /> Toggle <code>readOnly</code> for the entire table </label> </div> </div>
<HotTable ref={hotTableComponentRef} beforeChange={onBeforeHotChange} autoWrapRow={true} autoWrapCol={true} {...hotSettings} /> </div> <h3>Redux store dump</h3> <pre id="redux-preview" className="table-container"> {isHotData && ( <div> <strong>data:</strong> <table style={{ border: '1px solid #d6d6d6' }}> <tbody> {hotData.map((row, i) => ( <tr key={i}> {row.map((cell, i) => ( <td key={i}>{cell}</td> ))} </tr> ))} </tbody> </table> </div> )}
<table> <tbody> {Object.entries(hotSettings).map( ([name, value]) => name !== 'data' && ( <tr key={`${name}${value}`}> <td> <strong>{name}:</strong> </td> <td>{value.toString()}</td> </tr> ), )} </tbody> </table> </pre> </div> </div> );};
const initialReduxStoreState = { data: [ ['SKU-4821', 'Stainless Steel Water Bottle', 'Harbor Goods'], ['SKU-0093', 'Wireless Mouse', 'Alpine Supply Co.'], ['SKU-1170', 'Ergonomic Office Chair', 'Cascade Distributors'], ['SKU-2208', 'USB-C Charging Cable', 'Summit Trading'], ['SKU-3341', 'Aluminum Water Filter', 'Northgate Wholesale'], ], colHeaders: true, rowHeaders: true, readOnly: false, height: 'auto', // licenseKey: 'your-license-key', // get a key at https://handsontable.com/pricing/};
const updatesReducer = (state = initialReduxStoreState, action) => { switch (action.type) { case 'updateData': { let hasChanged = false; const newData = state.data.map((row) => [...row]);
action.dataChanges.forEach(([row, column, oldValue, newValue]) => { if (newData[row][column] !== newValue) { newData[row][column] = newValue; hasChanged = true; } });
// Return the previous state when no value actually changed. Plugins write to the grid on // their own (`mergeCells` clears the cells that a merge area covers), and handing back a new // state object every time would re-render the component and resend the settings in a loop. return hasChanged ? { ...state, data: newData } : state; }
case 'updateReadOnly': return { ...state, readOnly: action.readOnly, };
default: return state; }};
const reduxStore = createStore(updatesReducer);
const ExampleComponent = () => ( <Provider store={reduxStore}> <ExampleComponentContent /> </Provider>);
export default ExampleComponent;import { useRef, MouseEvent, JSXElementConstructor, Key, ReactElement, ReactNode, ReactPortal } from 'react';import { createStore } from 'redux';import { Provider, useSelector, useDispatch } from 'react-redux';import { HotTable } from '@handsontable/react-wrapper';import { registerAllModules } from 'handsontable/registry';import Handsontable from 'handsontable/base';
// register Handsontable's modulesregisterAllModules();
const ExampleComponentContent = () => { const hotSettings = useSelector((state: RootState) => state); const dispatch = useDispatch(); const hotTableComponentRef = useRef(null);
const hotData = hotSettings.data; const isHotData = Array.isArray(hotData);
const onBeforeHotChange = (changes: (Handsontable.CellChange | null)[]) => { dispatch({ type: 'updateData', dataChanges: changes, });
return false; };
const toggleReadOnly = (event: MouseEvent) => { dispatch({ type: 'updateReadOnly', readOnly: (event.target as HTMLInputElement).checked, }); };
return ( <div className="dump-example-container"> <div id="example-container"> <div id="example-preview"> <div className="example-controls-container"> <div className="controls"> <label> <input onClick={toggleReadOnly} type="checkbox" /> Toggle <code>readOnly</code> for the entire table </label> </div> </div>
<HotTable ref={hotTableComponentRef} beforeChange={onBeforeHotChange} autoWrapRow={true} autoWrapCol={true} {...hotSettings} /> </div> <h3>Redux store dump</h3> <pre id="redux-preview" className="table-container"> {isHotData && ( <div> <strong>data:</strong> <table style={{ border: '1px solid #d6d6d6' }}> <tbody> {hotData.map((row, i) => ( <tr key={i}> {row.map( ( cell: | string | number | boolean | ReactElement<any, string | JSXElementConstructor<any>> | Iterable<ReactNode> | ReactPortal | null | undefined, i: Key | null | undefined ) => ( <td key={i}>{cell}</td> ) )} </tr> ))} </tbody> </table> </div> )}
<table> <tbody> {Object.entries(hotSettings).map( ([name, value]) => name !== 'data' && ( <tr key={`${name}${value}`}> <td> <strong>{name}:</strong> </td> <td>{value.toString()}</td> </tr> ) )} </tbody> </table> </pre> </div> </div> );};
const initialReduxStoreState = { data: [ ['SKU-4821', 'Stainless Steel Water Bottle', 'Harbor Goods'], ['SKU-0093', 'Wireless Mouse', 'Alpine Supply Co.'], ['SKU-1170', 'Ergonomic Office Chair', 'Cascade Distributors'], ['SKU-2208', 'USB-C Charging Cable', 'Summit Trading'], ['SKU-3341', 'Aluminum Water Filter', 'Northgate Wholesale'], ], colHeaders: true, rowHeaders: true, readOnly: false, height: 'auto', // licenseKey: 'your-license-key', // get a key at https://handsontable.com/pricing/};
const updatesReducer = ( state = initialReduxStoreState, action: { type: any; dataChanges: [any, any, any, any][]; readOnly: any }) => { switch (action.type) { case 'updateData': { let hasChanged = false; const newData = state.data.map((row) => [...row]);
action.dataChanges.forEach(([row, column, oldValue, newValue]) => { if (newData[row][column] !== newValue) { newData[row][column] = newValue; hasChanged = true; } });
// Return the previous state when no value actually changed. Plugins write to the grid on // their own (`mergeCells` clears the cells that a merge area covers), and handing back a new // state object every time would re-render the component and resend the settings in a loop. return hasChanged ? { ...state, data: newData } : state; }
case 'updateReadOnly': return { ...state, readOnly: action.readOnly, };
default: return state; }};
export type RootState = ReturnType<typeof updatesReducer>;
const reduxStore = createStore(updatesReducer);
const ExampleComponent = () => ( <Provider store={reduxStore}> <ExampleComponentContent /> </Provider>);
export default ExampleComponent;Advanced example
This example shows:
- A custom editor component (built with an external dependency,
HexColorPicker). This component acts both as an editor and as a renderer. - A custom renderer component, built with a local
StarRatingcomponent.
The editor component changes the behavior of the renderer component, by passing information through Redux (and the connect() method of react-redux).
import { useEffect, useRef, useState } from 'react';import { HexColorPicker } from 'react-colorful';import { Provider, connect, useDispatch } from 'react-redux';import { createStore, combineReducers } from 'redux';import { HotTable, HotColumn, useHotEditor } from '@handsontable/react-wrapper';import { registerAllModules } from 'handsontable/registry';
// register Handsontable's modulesregisterAllModules();
function StarRating({ name, value = 0, starCount = 5, starColor = '#ffb400', emptyStarColor = '#d3d3d3' }) { return ( <div style={{ display: 'inline-flex', gap: '1px' }}> {Array.from({ length: starCount }, (_, i) => ( <span key={`${name}-${i + 1}`} style={{ fontSize: '18px', color: i + 1 <= value ? starColor : emptyStarColor, lineHeight: 1 }} > ★ </span> ))} </div> );}
const UnconnectedColorPickerEditor = () => { const dispatch = useDispatch(); const editorRef = useRef(null); const [pickedColor, setPickedColor] = useState(''); const { value, setValue, isOpen, finishEditing, col, row } = useHotEditor({ onOpen: () => { if (editorRef.current) editorRef.current.style.display = 'block'; document.querySelector('.react-colorful__interactive')?.focus(); }, onClose: () => { if (editorRef.current) editorRef.current.style.display = 'none'; setPickedColor(''); }, onPrepare: (_row, _column, _prop, TD, _originalValue, _cellProperties) => { const tdPosition = TD.getBoundingClientRect();
if (!editorRef.current) return; editorRef.current.style.left = `${tdPosition.left + window.pageXOffset}px`; editorRef.current.style.top = `${tdPosition.top + window.pageYOffset}px`; }, onFocus: () => {}, });
const onPickedColor = (color) => { setValue(color); };
const applyColor = () => { if (col === 1) { dispatch({ type: 'updateActiveStarColor', row, hexColor: value, }); } else if (col === 2) { dispatch({ type: 'updateInactiveStarColor', row, hexColor: value, }); }
finishEditing(); };
const stopMousedownPropagation = (e) => { e.stopPropagation(); };
const stopKeyboardPropagation = (e) => { e.stopPropagation();
if (e.key === 'Escape') { applyColor(); } };
return ( <div style={{ display: 'none', position: 'absolute', left: 0, top: 0, zIndex: 999, background: '#fff', padding: '15px', border: '1px solid #cecece', }} ref={editorRef} onMouseDown={stopMousedownPropagation} onKeyDown={stopKeyboardPropagation} > <HexColorPicker color={pickedColor || value} onChange={onPickedColor} /> <button style={{ width: '100%', height: '33px', marginTop: '10px' }} onClick={applyColor}> Apply </button> </div> );};
const ColorPickerEditor = connect(function (state) { return { activeColors: state.appReducer.activeColors, inactiveColors: state.appReducer.inactiveColors, };})(UnconnectedColorPickerEditor);
const ColorPickerRenderer = ({ value }) => { return ( <> <div style={{ background: value, width: '21px', height: '21px', float: 'left', marginRight: '5px', }} /> <div>{value}</div> </> );};
// a Redux componentconst initialReduxStoreState = { activeColors: [], inactiveColors: [],};
const appReducer = (state = initialReduxStoreState, action) => { switch (action.type) { case 'initRatingColors': { const { hotData } = action; const activeColors = hotData.map((data) => data[1]); const inactiveColors = hotData.map((data) => data[2]);
return { ...state, activeColors, inactiveColors, }; } case 'updateActiveStarColor': { const rowIndex = action.row; const newColor = action.hexColor; const activeColorArray = state.activeColors ? [...state.activeColors] : [];
activeColorArray[rowIndex] = newColor;
return { ...state, activeColors: activeColorArray, }; } case 'updateInactiveStarColor': { const rowIndex = action.row; const newColor = action.hexColor; const inactiveColorArray = state.inactiveColors ? [...state.inactiveColors] : [];
inactiveColorArray[rowIndex] = newColor;
return { ...state, inactiveColors: inactiveColorArray, }; } default: return state; }};
const actionReducers = combineReducers({ appReducer });const reduxStore = createStore(actionReducers);// a custom renderer componentconst UnconnectedStarRatingRenderer = ({ row, col, value, activeColors, inactiveColors }) => { return ( <StarRating name={`${row}-${col}`} value={value} starCount={5} starColor={activeColors?.[row || 0]} emptyStarColor={inactiveColors?.[row || 0]} /> );};
const StarRatingRenderer = connect((state) => ({ activeColors: state.appReducer.activeColors, inactiveColors: state.appReducer.inactiveColors,}))(UnconnectedStarRatingRenderer);
const data = [ [1, '#ff6900', '#fcb900'], [2, '#fcb900', '#7bdcb5'], [3, '#7bdcb5', '#8ed1fc'], [4, '#00d084', '#0693e3'], [5, '#eb144c', '#abb8c3'],];
const ExampleComponent = () => { useEffect(() => { reduxStore.dispatch({ type: 'initRatingColors', hotData: data, }); }, []);
return ( <Provider store={reduxStore}> <HotTable // licenseKey="your-license-key" // get a key at https://handsontable.com/pricing/ data={data} rowHeaders={true} rowHeights={30} colHeaders={['Rating', 'Active star color', 'Inactive star color']} height="auto" autoWrapRow={true} autoWrapCol={true} > <HotColumn width={100} type="numeric" renderer={StarRatingRenderer} /> <HotColumn width={150} renderer={ColorPickerRenderer} editor={ColorPickerEditor} /> <HotColumn width={150} renderer={ColorPickerRenderer} editor={ColorPickerEditor} /> </HotTable> </Provider> );};
export default ExampleComponent;import { useEffect, MouseEvent, KeyboardEvent, useRef, useState } from 'react';import Handsontable from 'handsontable/base';import { HexColorPicker } from 'react-colorful';import { Provider, connect, useDispatch } from 'react-redux';import { createStore, combineReducers } from 'redux';import { HotTable, HotColumn, useHotEditor } from '@handsontable/react-wrapper';import { registerAllModules } from 'handsontable/registry';
// register Handsontable's modulesregisterAllModules();
interface StarRatingProps { name: string; value?: number; starCount?: number; starColor?: string; emptyStarColor?: string;}
function StarRating({ name, value = 0, starCount = 5, starColor = '#ffb400', emptyStarColor = '#d3d3d3' }: StarRatingProps) { return ( <div style={{ display: 'inline-flex', gap: '1px' }}> {Array.from({ length: starCount }, (_, i) => ( <span key={`${name}-${i + 1}`} style={{ fontSize: '18px', color: i + 1 <= value ? starColor : emptyStarColor, lineHeight: 1 }} > ★ </span> ))} </div> );}
type RendererProps = { TD?: HTMLTableCellElement; value?: string | number; row?: number; col?: number; cellProperties?: Handsontable.CellProperties;};
const UnconnectedColorPickerEditor = () => { const dispatch = useDispatch(); const editorRef = useRef<HTMLDivElement>(null); const [pickedColor, setPickedColor] = useState('');
const { value, setValue, isOpen, finishEditing, col, row } = useHotEditor({ onOpen: () => { if (editorRef.current) editorRef.current.style.display = 'block'; (document.querySelector('.react-colorful__interactive') as HTMLDivElement)?.focus(); }, onClose: () => { if (editorRef.current) editorRef.current.style.display = 'none';
setPickedColor(''); }, onPrepare: (_row, _column, _prop, TD, _originalValue, _cellProperties) => { const tdPosition = TD.getBoundingClientRect();
if (!editorRef.current) return;
editorRef.current.style.left = `${tdPosition.left + window.pageXOffset}px`; editorRef.current.style.top = `${tdPosition.top + window.pageYOffset}px`; }, onFocus: () => {}, });
const onPickedColor = (color: string) => { setValue(color); };
const applyColor = () => { if (col === 1) { dispatch({ type: 'updateActiveStarColor', row, hexColor: value, }); } else if (col === 2) { dispatch({ type: 'updateInactiveStarColor', row, hexColor: value, }); }
finishEditing(); };
const stopMousedownPropagation = (e: MouseEvent) => { e.stopPropagation(); };
const stopKeyboardPropagation = (e: KeyboardEvent) => { e.stopPropagation();
if (e.key === 'Escape') { applyColor(); } };
return ( <div style={{ display: 'none', position: 'absolute', left: 0, top: 0, zIndex: 999, background: '#fff', padding: '15px', border: '1px solid #cecece', }} ref={editorRef} onMouseDown={stopMousedownPropagation} onKeyDown={stopKeyboardPropagation} > <HexColorPicker color={pickedColor || value} onChange={onPickedColor} /> <button style={{ width: '100%', height: '33px', marginTop: '10px' }} onClick={applyColor}> Apply </button> </div> );};
const ColorPickerEditor = connect(function (state: RootState) { return { activeColors: state.appReducer.activeColors, inactiveColors: state.appReducer.inactiveColors, };})(UnconnectedColorPickerEditor);
const ColorPickerRenderer = ({ value }: RendererProps) => { return ( <> <div style={{ background: value, width: '21px', height: '21px', float: 'left', marginRight: '5px', }} /> <div>{value}</div> </> );};
// a Redux componentconst initialReduxStoreState: { activeColors?: string[]; inactiveColors?: string[];} = { activeColors: [], inactiveColors: [],};
const appReducer = ( state = initialReduxStoreState, action: { type?: any; row?: any; hexColor?: any; hotData?: any }) => { switch (action.type) { case 'initRatingColors': { const { hotData } = action;
const activeColors = hotData.map((data: string[]) => data[1]); const inactiveColors = hotData.map((data: string[]) => data[2]);
return { ...state, activeColors, inactiveColors, }; }
case 'updateActiveStarColor': { const rowIndex = action.row; const newColor = action.hexColor;
const activeColorArray = state.activeColors ? [...state.activeColors] : [];
activeColorArray[rowIndex] = newColor;
return { ...state, activeColors: activeColorArray, }; }
case 'updateInactiveStarColor': { const rowIndex = action.row; const newColor = action.hexColor;
const inactiveColorArray = state.inactiveColors ? [...state.inactiveColors] : [];
inactiveColorArray[rowIndex] = newColor;
return { ...state, inactiveColors: inactiveColorArray, }; }
default: return state; }};
const actionReducers = combineReducers({ appReducer });const reduxStore = createStore(actionReducers);
type RootState = ReturnType<typeof actionReducers>;
// a custom renderer componentconst UnconnectedStarRatingRenderer = ({ row, col, value, activeColors, inactiveColors,}: { row?: number; col?: number; value?: number; activeColors?: string; inactiveColors?: string;}) => { return ( <StarRating name={`${row}-${col}`} value={value} starCount={5} starColor={activeColors?.[row || 0]} emptyStarColor={inactiveColors?.[row || 0]} /> );};
const StarRatingRenderer = connect((state: RootState) => ({ activeColors: state.appReducer.activeColors, inactiveColors: state.appReducer.inactiveColors,}))(UnconnectedStarRatingRenderer);
const data = [ [1, '#ff6900', '#fcb900'], [2, '#fcb900', '#7bdcb5'], [3, '#7bdcb5', '#8ed1fc'], [4, '#00d084', '#0693e3'], [5, '#eb144c', '#abb8c3'],];
const ExampleComponent = () => { useEffect(() => { reduxStore.dispatch({ type: 'initRatingColors', hotData: data, }); }, []);
return ( <Provider store={reduxStore}> <HotTable // licenseKey="your-license-key" // get a key at https://handsontable.com/pricing/ data={data} rowHeaders={true} rowHeights={30} colHeaders={['Rating', 'Active star color', 'Inactive star color']} height="auto" autoWrapRow={true} autoWrapCol={true} > <HotColumn width={100} type="numeric" renderer={StarRatingRenderer} /> <HotColumn width={150} renderer={ColorPickerRenderer} editor={ColorPickerEditor} /> <HotColumn width={150} renderer={ColorPickerRenderer} editor={ColorPickerEditor} /> </HotTable> </Provider> );};
export default ExampleComponent;Pass props from state
The React wrapper sends your props to the grid through updateSettings() on every render. Treat every prop as applied again each time the parent component re-renders. The wrapper skips only a few options whose value did not change: dataSchema, colWidths, rowHeights, minRowHeights, and columns when you pass it as a prop. With <HotColumn> children, the wrapper builds columns from them and sends it on every render.
A state change in the parent component — a toggle, a counter, a Redux action — therefore applies your props again. Three rules keep that harmless.
Pass data by reference
A new data array replaces the grid’s data and discards the user’s edits. Keep the array in a constant, useState, or useMemo. For the full explanation, see Binding to data.
Let the grid own what users change
Some options hold state that the grid changes while users work. mergeCells is one of them: users merge cells through the context menu or the API. Every render applies the mergeCells prop again, so the merge areas users created disappear on the next state change. This happens even when the array is a constant.
Leave the mergeCells prop out. Declare the initial areas once on the instance, and turn on the context menu so users can merge:
import { useEffect, useRef } from 'react';import { HotTable } from '@handsontable/react-wrapper';
const data = [ ['Harbor Goods', 'Seattle', 142], ['Alpine Supply Co.', 'Denver', 0],];
function InventoryGrid() { const hotRef = useRef(null);
useEffect(() => { hotRef.current.hotInstance.updateSettings({ mergeCells: [{ row: 0, col: 0, rowspan: 1, colspan: 2 }], }); }, []);
return ( <HotTable // licenseKey="your-license-key" // get a key at https://handsontable.com/pricing/ ref={hotRef} data={data} contextMenu /> );}The wrapper never sends mergeCells, so the merges users create stay through every re-render.
Do not copy the merges into state from the afterMergeCells and afterUnmergeCells hooks and pass them back as the prop. The hooks do not fire for undo and redo, or when inserting and removing rows shifts a merge. State then keeps the old area, and the next render puts it back and clears the cells it covers.
Clear a prop with undefined
When a prop that had a value becomes undefined, the wrapper sends the option’s default, so the grid goes back to it. null and false are real values, and the grid applies them as they are. A hook prop is the exception: a callback that becomes undefined, null, or false is removed.
<HotTable readOnly={locked ? true : undefined} />Two cases do not clear:
- A prop that you stop passing is not sent, so the grid keeps its last value.
{...(locked && { readOnly: true })}leavesreadOnlyon afterlockedturnsfalse. Passundefinedexplicitly, as above. A hook you stop passing is removed. - An option whose default is
undefinedcan ignore anundefinedvalue.heightandwidthkeep their last value. Passnullto remove a fixed size, or'auto'for the height.
<HotTable height={fullPage ? null : 400} />What you learned
- You can connect a
HotTablecomponent to a Redux store usingreact-redux’sconnect()method. - The
beforeChangehook dispatches Redux actions whenever a cell changes, keeping global state in sync. - A reducer that returns the previous state when nothing changed keeps plugin writes from looping with re-renders.
- Every render applies your props again, so keep
datastable and leave out the props of options that users change, such asmergeCells. - Custom editor and renderer components can read from and write to the Redux store, enabling grid cells to reflect shared application state.
Next steps
- Binding to data — understand how Handsontable binds to different data structures.
- Saving data — learn additional patterns for persisting grid changes.