Cell renderer
A cell renderer is a function that controls how Handsontable DataGrid displays cell content in the DOM. Override a built-in renderer or write your own to customize the visual output.
Use a cell renderer
You can use any of the built-in renderers by specifying their alias name in your column configuration. The example below shows how to use the numeric renderer, which formats numeric values according to the cell’s formatting options:
<HotTable data={someData} columns={[ { renderer: "numeric", }, ]}/>Declare a custom renderer as a component
Handsontable’s React wrapper lets you create custom cell renderers using React components.
To use your component as a Handsontable renderer, pass it in the renderer prop if either HotTable or HotColumn components, as you would with any other config option.
import { HotTable, HotColumn } from '@handsontable/react-wrapper';import { registerAllModules } from 'handsontable/registry';
// Register all Handsontable's modules.registerAllModules();
// your renderer componentconst RendererComponent = (props) => { // the available renderer-related props are: // - `row` (row index) // - `col` (column index) // - `prop` (column property name) // - `TD` (the HTML cell element) // - `cellProperties` (the `cellProperties` object for the edited cell) return ( <> <i style={{ color: '#a9a9a9' }}> Row: {props.row}, column: {props.col}, </i>{' '} value: {props.value} </> );};
const hotData = [ ['A1', 'B1', 'C1', 'D1', 'E1'], ['A2', 'B2', 'C2', 'D2', 'E2'], ['A3', 'B3', 'C3', 'D3', 'E3'], ['A4', 'B4', 'C4', 'D4', 'E4'], ['A5', 'B5', 'C5', 'D5', 'E5'], ['A6', 'B6', 'C6', 'D6', 'E6'], ['A7', 'B7', 'C7', 'D7', 'E7'], ['A8', 'B8', 'C8', 'D8', 'E8'], ['A9', 'B9', 'C9', 'D9', 'E9'],];
const ExampleComponent = () => { return ( <HotTable // licenseKey="your-license-key" // get a key at https://handsontable.com/pricing/ data={hotData} autoWrapRow={true} autoWrapCol={true} autoRowSize={false} autoColumnSize={false} height="auto" > <HotColumn width={250} renderer={RendererComponent} /> </HotTable> );};
export default ExampleComponent;import { HotTable, HotColumn } from '@handsontable/react-wrapper';import Handsontable from 'handsontable/base';import { registerAllModules } from 'handsontable/registry';
// Register all Handsontable's modules.registerAllModules();
type RendererProps = { TD?: HTMLTableCellElement; value?: string | number; row?: number; col?: number; cellProperties?: Handsontable.CellProperties;};
// your renderer componentconst RendererComponent = (props: RendererProps) => { // the available renderer-related props are: // - `row` (row index) // - `col` (column index) // - `prop` (column property name) // - `TD` (the HTML cell element) // - `cellProperties` (the `cellProperties` object for the edited cell) return ( <> <i style={{ color: '#a9a9a9' }}> Row: {props.row}, column: {props.col}, </i>{' '} value: {props.value} </> );};
const hotData = [ ['A1', 'B1', 'C1', 'D1', 'E1'], ['A2', 'B2', 'C2', 'D2', 'E2'], ['A3', 'B3', 'C3', 'D3', 'E3'], ['A4', 'B4', 'C4', 'D4', 'E4'], ['A5', 'B5', 'C5', 'D5', 'E5'], ['A6', 'B6', 'C6', 'D6', 'E6'], ['A7', 'B7', 'C7', 'D7', 'E7'], ['A8', 'B8', 'C8', 'D8', 'E8'], ['A9', 'B9', 'C9', 'D9', 'E9'],];
const ExampleComponent = () => { return ( <HotTable // licenseKey="your-license-key" // get a key at https://handsontable.com/pricing/ data={hotData} autoWrapRow={true} autoWrapCol={true} autoRowSize={false} autoColumnSize={false} height="auto" > <HotColumn width={250} renderer={RendererComponent} /> </HotTable> );};
export default ExampleComponent;A component in a cell is reused for another record after a sort, a filter, or a scroll. State from useState stays with the cell position, not with the record, so a value you set on one record can show on another. Keep state outside the component, keyed by the record. Resetting the state with a key or a useEffect clears it, but doesn’t move it to the record.
Use the renderer component within React’s context
In this example, React’s Context passes information available in the main app component to the renderer. In this case, we’re using just the renderer, but the same principle works with editors as well.
import { useState, useContext, createContext } from 'react';import { HotTable, HotColumn } from '@handsontable/react-wrapper';import { registerAllModules } from 'handsontable/registry';
// Register all Handsontable's modules.registerAllModules();
// a componentconst HighlightContext = createContext(false);
// a renderer componentfunction CustomRenderer(props) { const darkMode = useContext(HighlightContext);
if (!props.TD) return;
if (darkMode) { props.TD.className = 'dark'; } else { props.TD.className = ''; }
return <div>{props.value}</div>;}
const data = [['A1'], ['A2'], ['A3'], ['A4'], ['A5'], ['A6'], ['A7'], ['A8'], ['A9'], ['A10']];
const ExampleComponent = () => { const [darkMode, setDarkMode] = useState(false);
const toggleDarkMode = (event) => { setDarkMode(event.target.checked); };
return ( <HighlightContext.Provider value={darkMode}> <div className="example-controls-container"> <div className="controls"> <label> <input type="checkbox" onClick={toggleDarkMode} /> Dark mode </label> </div> </div> <HotTable // licenseKey="your-license-key" // get a key at https://handsontable.com/pricing/ data={data} rowHeaders={true} autoRowSize={false} autoColumnSize={false} height="auto" > <HotColumn renderer={CustomRenderer} /> </HotTable> </HighlightContext.Provider> );};
export default ExampleComponent;import { useState, useContext, MouseEvent, createContext } from 'react';import { HotTable, HotColumn } from '@handsontable/react-wrapper';import Handsontable from 'handsontable/base';import { registerAllModules } from 'handsontable/registry';
// Register all Handsontable's modules.registerAllModules();
type RendererProps = { TD?: HTMLTableCellElement; value?: string | number; row?: number; col?: number; cellProperties?: Handsontable.CellProperties;};
// a componentconst HighlightContext = createContext(false);
// a renderer componentfunction CustomRenderer(props: RendererProps) { const darkMode = useContext(HighlightContext);
if (!props.TD) return;
if (darkMode) { props.TD.className = 'dark'; } else { props.TD.className = ''; }
return <div>{props.value}</div>;}
const data = [['A1'], ['A2'], ['A3'], ['A4'], ['A5'], ['A6'], ['A7'], ['A8'], ['A9'], ['A10']];
const ExampleComponent = () => { const [darkMode, setDarkMode] = useState(false);
const toggleDarkMode = (event: MouseEvent) => { setDarkMode((event.target as HTMLInputElement).checked); };
return ( <HighlightContext.Provider value={darkMode}> <div className="example-controls-container"> <div className="controls"> <label> <input type="checkbox" onClick={toggleDarkMode} /> Dark mode </label> </div> </div> <HotTable // licenseKey="your-license-key" // get a key at https://handsontable.com/pricing/ data={data} rowHeaders={true} autoRowSize={false} autoColumnSize={false} height="auto" > <HotColumn renderer={CustomRenderer} /> </HotTable> </HighlightContext.Provider> );};
export default ExampleComponent;#example2 .handsontable td.dark { background: #000 !important; color: #fff !important;}
#example2 .handsontable td { background: #fff !important; color: #000 !important;}Declare a custom renderer as a function
You can also declare a custom renderer for the HotTable component by declaring it as a function. In the simplest scenario, you can pass the rendering function as the hotRenderer prop into HotTable or HotColumn.
If you need the renderer to be a part of a columns config array, declare it under the renderer key.
The following example implements @handsontable/react-wrapper with a custom renderer added to one of the columns. It takes an image URL as the input and renders the image in the edited cell.
import { HotTable } from '@handsontable/react-wrapper';import { registerAllModules } from 'handsontable/registry';
// register Handsontable's modulesregisterAllModules();
const data = [ ['A1', '/docs/img/examples/professional-javascript-developers-nicholas-zakas.jpg'], ['A2', '/docs/img/examples/javascript-the-good-parts.jpg'],];
const ExampleComponent = () => { return ( <HotTable // licenseKey="your-license-key" // get a key at https://handsontable.com/pricing/ id="hot" data={data} columns={[ {}, { renderer(instance, td, row, col, prop, value, cellProperties) { const img = document.createElement('img');
img.src = value;
img.addEventListener('mousedown', (event) => { event.preventDefault(); });
td.innerText = ''; td.appendChild(img);
return td; }, }, ]} colHeaders={true} minRowHeights={55} height="auto" autoWrapRow={true} autoWrapCol={true} /> );};
export default ExampleComponent;import { HotTable } from '@handsontable/react-wrapper';import { registerAllModules } from 'handsontable/registry';
// register Handsontable's modulesregisterAllModules();
const data = [ ['A1', '/docs/img/examples/professional-javascript-developers-nicholas-zakas.jpg'], ['A2', '/docs/img/examples/javascript-the-good-parts.jpg'],];
const ExampleComponent = () => { return ( <HotTable // licenseKey="your-license-key" // get a key at https://handsontable.com/pricing/ id="hot" data={data} columns={[ {}, { renderer(instance, td, row, col, prop, value, cellProperties) { const img = document.createElement('img');
img.src = value;
img.addEventListener('mousedown', (event) => { event.preventDefault(); });
td.innerText = ''; td.appendChild(img);
return td; }, }, ]} colHeaders={true} minRowHeights={55} height="auto" autoWrapRow={true} autoWrapCol={true} /> );};
export default ExampleComponent;Register custom cell renderer
To register your own alias use registerRenderer() function from the handsontable/renderers module. It takes two arguments:
rendererName- a string representing a renderer functionrenderer- a renderer function that will be represented byrendererName
If you’d like to register asteriskDecoratorRenderer under alias asterisk you have to call:
import { registerRenderer } from "handsontable/renderers";
registerRenderer("asterisk", asteriskDecoratorRenderer);Choose aliases wisely. If you register your renderer under name that is already registered, the target function will be overwritten:
import { registerRenderer } from "handsontable/renderers";
registerRenderer("text", asteriskDecoratorRenderer);Now "text" alias points to asteriskDecoratorRenderer function, not the built-in textRenderer.
So, unless you intentionally want to overwrite an existing alias, try to choose a unique name. A good practice is prefixing your aliases with some custom name (for example your GitHub username) to minimize the possibility of name collisions. This is especially important if you want to publish your renderer, because you never know aliases has been registered by the user who uses your renderer.
import { registerRenderer } from "handsontable/renderers";
registerRenderer("asterisk", asteriskDecoratorRenderer);Someone might already registered such alias
import { registerRenderer } from "handsontable/renderers";
registerRenderer("my.asterisk", asteriskDecoratorRenderer);That’s better.
Use an alias
The final touch is to use registered aliases. That way users can easily refer to an alias without the need to know the name of the function.
To sum up, a well prepared renderer function should look like this:
import { registerRenderer } from "handsontable/renderers";
function customRenderer( hotInstance, td, row, column, prop, value, cellProperties) { // ...your custom logic of the renderer}
// Register an aliasregisterRenderer("my.custom", customRenderer);From now on, you can use customRenderer like so:
<HotTable data={someData} columns={[ { renderer: "my.custom", }, ]}/>When your custom renderer should preserve the default text output, call the built-in textRenderer() first. See Extend a built-in renderer.
Extend a built-in renderer
When you build on top of a built-in renderer such as textRenderer or htmlRenderer, Handsontable doesn’t call it for you. You call it inside your custom renderer, before your extra logic.
Use textRenderer when you want plain-text output and then apply styling or additional DOM changes.
Use htmlRenderer when your output is trusted HTML and you intentionally render with innerHTML.
Skip the built-in renderer when your renderer fully controls cell output from scratch, for example the image-based coverRenderer in Render custom HTML in cells.
The simplest way to write such a renderer is rendererFactory(). It passes all the cell arguments to your callback as a single object, so the callback receives everything by name. Write the callback as a regular function or an arrow function:
import { rendererFactory, textRenderer } from "handsontable/renderers";
const customRenderer = rendererFactory( ({ instance, td, row, column, prop, value, cellProperties }) => { textRenderer(instance, td, row, column, prop, value, cellProperties);
td.style.fontWeight = "bold"; });If you write a plain renderer function instead, you can call the built-in renderer in one of two ways:
// Direct invocation style, common in ESM and TypeScript examples.// Works in a `function` declaration and in an arrow function.textRenderer(instance, td, row, column, prop, value, cellProperties);
// Legacy style, common in classic JavaScript examples.// Use it inside a `function` declaration or a `function` expression.textRenderer.apply(this, arguments);Handsontable runs baseRenderer for you
baseRenderer is a separate renderer, and it isn’t one of the renderers described above. It adds the cell’s class names and ARIA attributes, including className, readOnly, and the invalid-cell class.
Since version 17.0.0, Handsontable runs baseRenderer for you. It runs after your custom renderer, whenever your renderer didn’t run it. Your cells keep their class names even when your renderer calls no built-in renderer at all. Before version 17.0.0, such cells received no class names.
Call baseRenderer yourself when you need it to run before your changes — for example, when your renderer sets a class that baseRenderer also manages, such as the invalid-cell class. A baseRenderer that runs last removes that class.
Render custom HTML in cells
This example shows how to use custom cell renderers to display HTML content in a cell. This is a very powerful feature. Just remember to escape any HTML code that could be used for XSS attacks.
In the below configuration:
- Title column uses built-in HTML renderer that allows any HTML. This is unsafe if your data comes from an untrusted source. A Handsontable user can enter
<script>or other potentially malicious tags using the cell editor. - Description column also uses HTML renderer (same as above)
- Comments column uses a custom renderer (
safeHtmlRenderer). This should be safe for user input, because only certain tags are allowed - Cover column accepts image URL as a string and converts it to a
<img>in the renderer
import { HotTable } from '@handsontable/react-wrapper';import { registerAllModules } from 'handsontable/registry';
// register Handsontable's modulesregisterAllModules();
const ExampleComponent = () => { const data = [ { title: '<a href="https://www.amazon.com/Professional-JavaScript-Developers-Nicholas-Zakas/dp/1118026691">Professional JavaScript for Web Developers</a>', description: 'This <a href="https://www.amazon.com/Professional-JavaScript-Developers-Nicholas-Zakas/dp/1118026691">book</a> provides a developer-level introduction along with more advanced and useful features of <b>JavaScript</b>.', comments: 'I would rate it ★★★★☆', cover: '/docs/img/examples/professional-javascript-developers-nicholas-zakas.jpg', }, { title: '<a href="https://shop.oreilly.com/product/9780596517748.do">JavaScript: The Good Parts</a>', description: 'This book provides a developer-level introduction along with <b>more advanced</b> and useful features of JavaScript.', comments: 'This is the book about JavaScript', cover: '/docs/img/examples/javascript-the-good-parts.jpg', }, { title: '<a href="https://shop.oreilly.com/product/9780596805531.do">JavaScript: The Definitive Guide</a>', description: '<em>JavaScript: The Definitive Guide</em> provides a thorough description of the core <b>JavaScript</b> language and both the legacy and standard DOMs implemented in web browsers.', comments: 'I\'ve never actually read it, but the <a href="https://shop.oreilly.com/product/9780596805531.do">comments</a> are highly <strong>positive</strong>.', cover: '/docs/img/examples/javascript-the-definitive-guide.jpg', }, ];
function safeHtmlRenderer(_instance, td, _row, _col, _prop, value, _cellProperties) { // WARNING: Be sure you only allow certain HTML tags to avoid XSS threats. // Sanitize the "value" before passing it to the innerHTML property. td.innerHTML = value; }
function coverRenderer(_instance, td, _row, _col, _prop, value, _cellProperties) { const img = document.createElement('img');
img.src = value; img.addEventListener('mousedown', (event) => { event.preventDefault(); }); td.innerText = ''; td.appendChild(img);
return td; }
return ( <HotTable // licenseKey="your-license-key" // get a key at https://handsontable.com/pricing/ data={data} colWidths={[200, 200, 200, 80]} colHeaders={['Title', 'Description', 'Comments', 'Cover']} height="auto" columns={[ { data: 'title', renderer: 'html' }, { data: 'description', renderer: 'html' }, { data: 'comments', renderer: safeHtmlRenderer }, { data: 'cover', renderer: coverRenderer }, ]} autoWrapRow={true} autoWrapCol={true} /> );};
export default ExampleComponent;import { HotTable } from '@handsontable/react-wrapper';import Handsontable from 'handsontable/base';import { registerAllModules } from 'handsontable/registry';
// register Handsontable's modulesregisterAllModules();
const ExampleComponent = () => { const data = [ { title: '<a href="https://www.amazon.com/Professional-JavaScript-Developers-Nicholas-Zakas/dp/1118026691">Professional JavaScript for Web Developers</a>', description: 'This <a href="https://www.amazon.com/Professional-JavaScript-Developers-Nicholas-Zakas/dp/1118026691">book</a> provides a developer-level introduction along with more advanced and useful features of <b>JavaScript</b>.', comments: 'I would rate it ★★★★☆', cover: '/docs/img/examples/professional-javascript-developers-nicholas-zakas.jpg', }, { title: '<a href="https://shop.oreilly.com/product/9780596517748.do">JavaScript: The Good Parts</a>', description: 'This book provides a developer-level introduction along with <b>more advanced</b> and useful features of JavaScript.', comments: 'This is the book about JavaScript', cover: '/docs/img/examples/javascript-the-good-parts.jpg', }, { title: '<a href="https://shop.oreilly.com/product/9780596805531.do">JavaScript: The Definitive Guide</a>', description: '<em>JavaScript: The Definitive Guide</em> provides a thorough description of the core <b>JavaScript</b> language and both the legacy and standard DOMs implemented in web browsers.', comments: 'I\'ve never actually read it, but the <a href="https://shop.oreilly.com/product/9780596805531.do">comments</a> are highly <strong>positive</strong>.', cover: '/docs/img/examples/javascript-the-definitive-guide.jpg', }, ];
function safeHtmlRenderer( _instance: Handsontable, td: HTMLTableCellElement, _row: number, _col: number, _prop: string | number, value: Handsontable.CellValue, _cellProperties: Handsontable.CellProperties ) { // WARNING: Be sure you only allow certain HTML tags to avoid XSS threats. // Sanitize the "value" before passing it to the innerHTML property. td.innerHTML = value; }
function coverRenderer( _instance: Handsontable, td: HTMLTableCellElement, _row: number, _col: number, _prop: string | number, value: Handsontable.CellValue, _cellProperties: Handsontable.CellProperties ) { const img = document.createElement('img');
img.src = value;
img.addEventListener('mousedown', (event) => { event.preventDefault(); });
td.innerText = ''; td.appendChild(img);
return td; }
return ( <HotTable // licenseKey="your-license-key" // get a key at https://handsontable.com/pricing/ data={data} colWidths={[200, 200, 200, 80]} colHeaders={['Title', 'Description', 'Comments', 'Cover']} height="auto" columns={[ { data: 'title', renderer: 'html' }, { data: 'description', renderer: 'html' }, { data: 'comments', renderer: safeHtmlRenderer }, { data: 'cover', renderer: coverRenderer }, ]} autoWrapRow={true} autoWrapCol={true} /> );};
export default ExampleComponent;Render hyperlinks in cells
A common use of a custom renderer is to turn a cell value into a clickable hyperlink. The renderer reads the cell value, builds an anchor (<a>) element, and appends it to the cell’s DOM node.
function hyperlinkRenderer(instance, td, row, column, prop, value, cellProperties) { Handsontable.dom.empty(td);
const link = document.createElement('a');
link.href = value; link.textContent = value; link.target = '_blank'; link.rel = 'noopener noreferrer';
td.appendChild(link);
return td;}Assign the renderer to a column through the renderer option, or register it by alias with registerRenderer() as shown in Register custom cell renderer.
Render custom HTML in header
You can also put HTML into row and column headers. If you need to attach events to DOM elements like the checkbox below, just remember to identify the element by class name, not by id. This is because row and column headers are duplicated in the DOM tree and id attribute must be unique.
If your goal is to extend a built-in renderer before adding custom logic, see Extend a built-in renderer.
import { useRef } from 'react';import { HotTable } from '@handsontable/react-wrapper';import { registerAllModules } from 'handsontable/registry';import { textRenderer } from 'handsontable/renderers/textRenderer';
// register Handsontable's modulesregisterAllModules();
const ALLOWED_TAGS = ['B', 'EM', 'INPUT', 'BR', 'TABLE', 'THEAD', 'TBODY', 'TR', 'TD', 'TH'];const ALLOWED_ATTRIBUTES = ['type', 'class', 'checked', 'colspan', 'rowspan'];const DROPPED_TAGS = ['SCRIPT', 'STYLE', 'TEXTAREA', 'TITLE'];
// Handsontable has no built-in sanitizer since v18.0, and `sanitizer` is grid-level:// it also filters pasted HTML, so the table tags have to survive -- otherwise pasting// a range degrades to plain text. In production, use a vetted library such as DOMPurify.// See https://handsontable.com/docs/security/const sanitizeHeader = (html) => { const template = document.createElement('template');
template.innerHTML = html;
template.content.querySelectorAll('*').forEach((element) => { if (DROPPED_TAGS.includes(element.tagName)) { // Unwrapping these would promote their source text into the output element.remove(); } else if (ALLOWED_TAGS.includes(element.tagName)) { Array.from(element.attributes).forEach((attribute) => { if (!ALLOWED_ATTRIBUTES.includes(attribute.name)) { element.removeAttribute(attribute.name); } }); } else { // Unwrap a disallowed element, keeping its text content element.replaceWith(...Array.from(element.childNodes)); } });
return template.innerHTML;};
const ExampleComponent = () => { const hotRef = useRef(null); let isChecked = false;
function customRenderer(_instance, td) { textRenderer.apply(this, arguments);
if (isChecked) { td.style.backgroundColor = 'yellow'; } else { td.style.backgroundColor = 'rgba(255,255,255,0.1)'; } }
const exampleContainerMouseupCallback = (event) => { const hot = hotRef.current?.hotInstance;
if (event.target.nodeName == 'INPUT' && event.target.className == 'checker') { isChecked = !event.target.checked; hot?.render(); } };
return ( <div id="exampleContainer5" onMouseUp={(...args) => exampleContainerMouseupCallback(...args)}> <HotTable // licenseKey="your-license-key" // get a key at https://handsontable.com/pricing/ ref={hotRef} height="auto" columns={[{}, { renderer: customRenderer }]} colHeaders={function (col) { switch (col) { case 0: return '<b>Bold</b> and <em>Beautiful</em>'; case 1: return `Some <input type="checkbox" class="checker" ${isChecked ? `checked="checked"` : ''}> checkbox`; default: return ''; } }} autoWrapRow={true} autoWrapCol={true} sanitizer={sanitizeHeader} /> </div> );};
export default ExampleComponent;import { useRef, MouseEvent } from 'react';import Handsontable from 'handsontable/base';import { HotTable, HotTableRef } from '@handsontable/react-wrapper';import { registerAllModules } from 'handsontable/registry';import { textRenderer } from 'handsontable/renderers/textRenderer';
// register Handsontable's modulesregisterAllModules();
const ALLOWED_TAGS = ['B', 'EM', 'INPUT', 'BR', 'TABLE', 'THEAD', 'TBODY', 'TR', 'TD', 'TH'];const ALLOWED_ATTRIBUTES = ['type', 'class', 'checked', 'colspan', 'rowspan'];const DROPPED_TAGS = ['SCRIPT', 'STYLE', 'TEXTAREA', 'TITLE'];
// Handsontable has no built-in sanitizer since v18.0, and `sanitizer` is grid-level:// it also filters pasted HTML, so the table tags have to survive -- otherwise pasting// a range degrades to plain text. In production, use a vetted library such as DOMPurify.// See https://handsontable.com/docs/security/const sanitizeHeader = (html: string): string => { const template = document.createElement('template');
template.innerHTML = html;
template.content.querySelectorAll('*').forEach((element) => { if (DROPPED_TAGS.includes(element.tagName)) { // Unwrapping these would promote their source text into the output element.remove(); } else if (ALLOWED_TAGS.includes(element.tagName)) { Array.from(element.attributes).forEach((attribute) => { if (!ALLOWED_ATTRIBUTES.includes(attribute.name)) { element.removeAttribute(attribute.name); } }); } else { // Unwrap a disallowed element, keeping its text content element.replaceWith(...Array.from(element.childNodes)); } });
return template.innerHTML;};
const ExampleComponent = () => { const hotRef = useRef<HotTableRef>(null);
let isChecked = false;
function customRenderer(this: Handsontable, _instance: Handsontable, td: HTMLTableCellElement) { textRenderer.apply(this, arguments as any);
if (isChecked) { td.style.backgroundColor = 'yellow'; } else { td.style.backgroundColor = 'rgba(255,255,255,0.1)'; } }
const exampleContainerMouseupCallback = (event: MouseEvent) => { const hot = hotRef.current?.hotInstance;
if ( (event.target as HTMLInputElement).nodeName == 'INPUT' && (event.target as HTMLInputElement).className == 'checker' ) { isChecked = !(event.target as HTMLInputElement).checked; hot?.render(); } };
return ( <div id="exampleContainer5" onMouseUp={(...args) => exampleContainerMouseupCallback(...args)}> <HotTable // licenseKey="your-license-key" // get a key at https://handsontable.com/pricing/ ref={hotRef} height="auto" columns={[{}, { renderer: customRenderer }]} colHeaders={function (col: number) { switch (col) { case 0: return '<b>Bold</b> and <em>Beautiful</em>';
case 1: return `Some <input type="checkbox" class="checker" ${isChecked ? `checked="checked"` : ''}> checkbox`;
default: return ''; } }} autoWrapRow={true} autoWrapCol={true} sanitizer={sanitizeHeader} /> </div> );};
export default ExampleComponent;Add event listeners in cell renderer function
If you are writing an advanced cell renderer, and you want to add some custom behavior after a certain user action (i.e. after user hover a mouse pointer over a cell) you might be tempted to add an event listener directly to table cell node passed as an argument to the renderer function. Unfortunately, this will almost always cause you trouble and you will end up with either performance issues or having the listeners attached to the wrong cell.
This is because Handsontable:
- Calls
rendererfunctions multiple times per cell - this can lead to having multiple copies of the same event listener attached to a cell - Reuses table cell nodes during table scrolling and adding/removing new rows/columns - this can lead to having event listeners attached to the wrong cell
Before deciding to attach an event listener in cell renderer make sure, that there is no Handsontable event that suits your needs. Using Handsontable events system is the safest way to respond to user actions.
If you did’t find a suitable Handsontable event put the cell content into a wrapping <div>, attach the event listener to the wrapper and then put it into the table cell.
Changes made outside a renderer do not survive
Handsontable reuses td elements as you scroll, sort, filter, and load data. Before it paints a cell with a renderer, it resets only part of the element:
- Cleared before each repaint: the
classattribute, the inlinestyle, thedirattribute, and the accessibility attributes. The reset removes every attribute whose name containsroleoraria-, so it also removesdata-roleanddata-aria-label. - Kept on the reused cell: other
data-*attributes, thetitleattribute, child nodes, event listeners (see Add event listeners in cell renderer function), and properties that your code assigns to the element.
What a renderer leaves behind in the second group shows up on whichever record the cell displays next. A stale tag, tooltip, or data-* attribute then appears on the wrong row. Understanding rendering explains when a render happens.
To keep a reused cell correct, follow this rule: on every render, empty the cell, and set or remove every attribute your renderer uses. Don’t write an attribute only when a condition is true.
// Do not do this. The cell keeps the attribute after it shows another record.if (value === 'Blocked') { td.setAttribute('data-status', 'blocked');}
// Do this instead. The attribute matches the current value on every render.if (value === 'Blocked') { td.setAttribute('data-status', 'blocked');} else { td.removeAttribute('data-status');}Built-in content renderers, such as textRenderer, replace the cell’s content. A custom renderer that calls one first, as the Extend a built-in renderer section shows, starts from clean content. A renderer that builds its own nodes empties the cell itself, for example with td.textContent = '', before it appends them.
The afterRenderer hook runs on the same reused td, after the renderer. Don’t empty the cell there, because that removes the value the renderer just wrote. Remove any node you added on an earlier call, then set or remove every attribute you use, on every call.
You have two supported ways to make a visual change stick:
-
Store it in the cell’s metadata, so that a built-in renderer reapplies it on every render. Because
setCellMeta()does not repaint the grid, follow it withrender():hot.setCellMeta(0, 0, 'className', 'my-highlight');hot.render(); -
Write a custom renderer. A renderer runs on every render, so what it writes is always reapplied. If your renderer reads state outside the grid and the grid uses
renderMode: 'onChange', setrenderMode: 'always'on its cells, or callmarkCellChanged()after that state changes.
For the full picture of when a render happens and what it covers, see Understanding rendering.
Add a tooltip to a cell
To show a description when users hover over a cell, set the HTML title attribute of the cell’s td element in a custom renderer. The browser displays the attribute’s value as a native tooltip. Browsers show a title tooltip only on mouse hover, so keyboard and touch users usually don’t see it, and screen readers can ignore it on a grid cell. Don’t put information that users need only in the tooltip.
Setting title in a cell’s configuration does not work. The title option sets a column header’s label, so cells: () => ({ title: 'Description' }) adds no title attribute to the td. Set the attribute on the element in the renderer.
Because Handsontable reuses cells, a td can still hold the title of a record that was rendered in it earlier. To avoid showing the wrong tooltip, set the attribute when a cell has a description and remove it when it doesn’t, on every call of the renderer.
If the renderer reads state from outside the grid, as the descriptions lookup below does, and the grid uses renderMode: 'onChange', see Changes made outside a renderer do not survive.
The renderer below calls the built-in text renderer first, then sets or removes title based on the cell’s value. Assign it to the renderer option of the column that shows the description:
import { textRenderer } from 'handsontable/renderers/textRenderer';
const descriptions = new Map([ ['SKU-4821', 'Back in stock on 2025-07-14.'], ['SKU-0093', 'Discontinued by the supplier.'],]);
const tooltipRenderer = (hot, td, row, column, prop, value, cellProperties) => { textRenderer(hot, td, row, column, prop, value, cellProperties);
const description = descriptions.get(value);
if (description) { td.title = description; } else { td.removeAttribute('title'); }
return td;};
// Pass it to <HotTable columns={columns} />:const columns = [{ renderer: tooltipRenderer }, {}];If you need a tooltip that keyboard users can reach, or one with your own markup, render your own element instead of title. Show it from afterOnCellMouseOver and hide it in afterOnCellMouseOut. Also show it from afterSelectionEnd and hide it in afterDeselect, so that moving the selection with the arrow keys shows it too. In afterOnCellMouseOut, show the tip of the selected cell again instead of hiding it, so that a mouse pass doesn’t hide the tip of a cell the keyboard has selected.
To attach a note that users can add, edit, and delete, use the comments plugin instead of a tooltip.
Performance considerations
Cell renderers are called separately for every displayed cell, during every table render. Table can be rendered multiple times during its lifetime (after table scroll, after table sorting, after cell edit etc.), therefore you should keep your renderer functions as simple and fast as possible or you might experience a performance drop, especially when dealing with large sets of data.
If you only need to format the displayed value (e.g., add units, format dates, or apply text transformations), consider using the valueFormatter option instead of a custom renderer. The valueFormatter is called before the renderer and focuses solely on value transformation, making it more performant for simple formatting tasks. Use a renderer when you need to modify the DOM structure, add custom HTML elements, or handle complex visual layouts.
When a renderer computes something slow from the cell’s data — a chart, a parsed document, a formatted summary — compute it once and reuse it. Key that cache by the data record or by the cell coordinates, never by the td element: the grid reuses each td for a different record as you scroll, so a td-keyed cache misses on almost every call. The Cache the output of an expensive cell renderer recipe walks through the pattern, including how to invalidate the cache when the data changes.
Result
You now have a custom cell renderer that controls how cell content appears in the DOM. You can use a built-in renderer by alias, register and reuse your own with registerRenderer(), or write inline renderer functions for full control over the cell’s HTML structure.
Related API
Overview
A renderer is a function that determines how a cell looks. It’s responsible for the complete cell rendering process, including DOM structure creation, content insertion, applying CSS classes, setting accessibility attributes, and managing all visual aspects of the cell.
Built-in renderers
Handsontable provides 10 built-in renderers that you can use by their alias names. Each renderer is designed for a specific use case:
| Alias | What the renderer does |
|---|---|
autocomplete | Renders autocomplete cells with suggestions |
checkbox | Renders checkbox cells for boolean values or values defined by checkedTemplate and uncheckedTemplate options |
date | Renders date values with date formatting |
dropdown | Renders dropdown cells with select options |
html | Renders HTML content in cells (allows raw HTML) |
numeric | Renders numeric values with number formatting |
password | Renders password fields (masks the displayed value) |
text | Renders plain text (default renderer) |
time | Renders time values with time formatting |
Using aliases provides a convenient way to specify which renderer should be used without needing to reference the full renderer function. You can change the renderer function associated with an alias without modifying the code that uses it.
renderer vs valueFormatter
Handsontable provides two distinct options for controlling how cell values are displayed: valueFormatter and renderer. This section provides a detailed comparison to help you choose the right tool for your use case.
What is renderer?
The renderer option is a function responsible for the complete cell rendering process. It handles DOM structure creation, content insertion (via innerText or innerHTML), applying CSS classes, setting accessibility attributes, and managing all visual aspects of the cell.
Function signature:
renderer(hotInstance, td, row, col, prop, value, cellProperties)When to use renderer:
- Modify DOM structure (add icons, custom HTML elements, complex layouts)
- Apply custom styling or CSS classes dynamically
- Handle accessibility attributes
- Create interactive elements within cells
- When you need full control over the cell’s HTML structure
Example:
function customRenderer(hotInstance, td, row, col, prop, value, cellProperties) { // Create custom DOM structure td.innerHTML = ` <div class="custom-wrapper"> <span class="icon">📊</span> <span class="value">${value}</span> </div> `;}What is valueFormatter?
The valueFormatter option (available since v17.0.0) is a function that transforms cell values before they are displayed. It focuses solely on value transformation and is called by the rendering engine right before the renderer function executes.
Function signature:
valueFormatter(value, cellProperties) => formattedValueWhen to use valueFormatter:
- Transform displayed values (add prefix, suffix, units)
- Format dates, numbers, or text in a custom way
- Apply simple text transformations
- When you only need to change what is displayed, not how it’s rendered
Example:
columns={[{ data: 'price', valueFormatter(value) { return value ? `$${value.toFixed(2)}` : ''; }}]}Key differences
| Aspect | valueFormatter | renderer |
|---|---|---|
| Purpose | Transform the value | Complete cell rendering |
| Scope | Value transformation only | DOM structure, styling, accessibility |
| Performance | Faster (called before renderer) | More overhead (full DOM manipulation) |
| Use case | Simple formatting (units, prefixes) | Complex layouts, custom HTML |
| Returns | Formatted value | Nothing (modifies DOM directly) |
Using renderer and valueFormatter together
Using both renderer and valueFormatter together is recommended when you need both value formatting and custom DOM structure. This approach separates concerns: valueFormatter handles value transformation, while renderer focuses on DOM manipulation. This separation improves maintainability and code clarity. The valueFormatter executes first, transforming the value, and then the renderer receives the formatted value:
columns={[{ data: 'amount', valueFormatter(value) { return `$${value.toFixed(2)}`; }, renderer(hotInstance, TD, row, col, prop, value, cellProperties) { TD.innerHTML = `<div class="amount-cell"><span class="currency">${value}</span></div>`; }}]}In this example, valueFormatter adds the currency symbol and formatting, while renderer wraps it in a custom DOM structure with additional styling.
Format symbols outside the Intl standard
The numeric renderer’s numericFormat option formats numbers through Intl.NumberFormat, which only recognizes ISO 4217 currency codes and a fixed list of ECMA-402 sanctioned units. Symbols outside that list, such as the Bitcoin symbol (₿) or per mille (‰), aren’t available through numericFormat. Attach them with valueFormatter instead:
import { HotTable } from '@handsontable/react-wrapper';import { registerAllModules } from 'handsontable/registry';
// register Handsontable's modulesregisterAllModules();
const ExampleComponent = () => { const data = [ { asset: 'Bitcoin', btcValue: 12.45, portfolioShare: 452 }, { asset: 'Ethereum', btcValue: 3.82, portfolioShare: 268 }, { asset: 'Solana', btcValue: 1.15, portfolioShare: 134 }, { asset: 'Cardano', btcValue: 0.47, portfolioShare: 81 }, { asset: 'Polkadot', btcValue: 0.29, portfolioShare: 65 }, ];
return ( <HotTable // licenseKey="your-license-key" // get a key at https://handsontable.com/pricing/ data={data} colHeaders={['Asset', 'BTC-equivalent value', 'Portfolio share']} columns={[ { data: 'asset' }, { data: 'btcValue', type: 'numeric', // Bitcoin (₿) isn't an ISO 4217 currency, so `numericFormat` can't format it. // `valueFormatter` prepends the symbol instead. valueFormatter(value) { // `type: 'numeric'` turns numeric input into a number, but invalid input // stays a string, so check the type before calling `toFixed()`. if (typeof value !== 'number') { return value; }
return `₿${value.toFixed(4)}`; }, }, { data: 'portfolioShare', // Per mille (‰) isn't a unit sanctioned by `Intl.NumberFormat`, so `valueFormatter` // appends the symbol manually. valueFormatter(value) { return `${value}‰`; }, }, ]} height="auto" /> );};
export default ExampleComponent;import { HotTable } from '@handsontable/react-wrapper';import { registerAllModules } from 'handsontable/registry';
// register Handsontable's modulesregisterAllModules();
const ExampleComponent = () => { const data = [ { asset: 'Bitcoin', btcValue: 12.45, portfolioShare: 452 }, { asset: 'Ethereum', btcValue: 3.82, portfolioShare: 268 }, { asset: 'Solana', btcValue: 1.15, portfolioShare: 134 }, { asset: 'Cardano', btcValue: 0.47, portfolioShare: 81 }, { asset: 'Polkadot', btcValue: 0.29, portfolioShare: 65 }, ];
return ( <HotTable // licenseKey="your-license-key" // get a key at https://handsontable.com/pricing/ data={data} colHeaders={['Asset', 'BTC-equivalent value', 'Portfolio share']} columns={[ { data: 'asset' }, { data: 'btcValue', type: 'numeric', // Bitcoin (₿) isn't an ISO 4217 currency, so `numericFormat` can't format it. // `valueFormatter` prepends the symbol instead. valueFormatter(value: unknown) { // `type: 'numeric'` turns numeric input into a number, but invalid input // stays a string, so check the type before calling `toFixed()`. if (typeof value !== 'number') { return value; }
return `₿${value.toFixed(4)}`; }, }, { data: 'portfolioShare', // Per mille (‰) isn't a unit sanctioned by `Intl.NumberFormat`, so `valueFormatter` // appends the symbol manually. valueFormatter(value: unknown) { return `${value}‰`; }, }, ]} height="auto" /> );};
export default ExampleComponent;Configuration options and API
APIs
Configuration options
Core methods
Hooks