Render functions (renderers) are functions that return a string which is rendered via {@html}. They are ideal for simple HTML customization and work even when using Svelecte as a custom element outside of Svelte. Highlighting is handled automatically unless you choose to handle it manually using the inputValue parameter.
Renderer Signature:
/**
* @param {object} item - The current option object
* @param {boolean} [selectionSection] - True if the option is being rendered in the control (selection area), false if in the dropdown
* @param {string} [inputValue] - The current search/input value (use this if you want to handle highlighting manually)
* @returns {string} - HTML string to render
*/
function renderer(item, selectionSection, inputValue) {}
Usage Patterns:
- Global Registration: Use
addRenderer(name, renderer) to make a renderer available by name via the renderer prop. - Local Usage: Pass the function directly to the
renderer prop.
Note: If you use inputValue to manually highlight text, you are responsible for escaping HTML tags to prevent XSS.
import Svelecte, { addRenderer } from 'svelecte';
// 1. Define the renderer
function colorRenderer(item, _isSelection, _inputValue) {
return _isSelection
? `<div style="width:16px; height: 16px; background-color: ${item.hex};"></div>${item.text}`
: `${item.text} (#${item.hex})`;
}
// 2. Register globally
addRenderer('color', colorRenderer);
// 3. Use it
// Via name:
<Svelecte renderer="color" options={options} />
// Or via function directly:
<Svelecte renderer={colorRenderer} options={options} />