In CdsAutocomplete, CdsCombobox and CdsSelect the highlighting of the matches is already built in — a standalone
CdsHighlightis not needed there. For a permanent label next to the text take CdsTag, for a counter take CdsBadge.
Variations
Search query
The text prop takes the source string, query takes what the user was looking for. The query can be a string or an array of terms: all of them get highlighted.
All occurrences
By default the first occurrence of every term is highlighted. The match-all prop highlights all of them — in a long text this shows the full picture.
Case
The ignore-case prop looks for matches regardless of the case. You need it almost always when the query is typed by the user.
Ready ranges
When the matches are found by the server rather than by the browser, pass them into matches — an array of [start, end] pairs by the indexes of the source string. The ranges take precedence over query, and overlapping ones are merged automatically.
Color and density
The color prop sets the color of the highlighting — the background is tinted with it too, so a single value is enough. opacity changes the density of the background.
Markup
The tag prop sets the tag of the wrapper (span by default), mark-class adds your own class to every match.
Guidelines
Scenarios
Searching through a list
The same query filters the list and highlights the matches in the found rows. match-all and ignore-case keep the highlighting and the filter consistent: once a row made it into the results, the match inside it is visible.
A query of several words
Split the typed phrase into words and pass them as an array into query — the component highlights every word separately, even if they stand far apart in the text.
Matches from the server
The full-text search on the backend already knows which fragments count as matches: it accounts for morphology, synonyms and typos. Give those ranges to matches — the client will not search anything again.
API
Props
| Name | Type | Default | Description |
|---|---|---|---|
color | string | undefined | — | Color of the highlighted text. |
ignoreCase | boolean | undefined | — | Ignores the case when searching by query. |
markClass | string | undefined | — | Extra CSS class for the <mark> element. |
matchAll | boolean | undefined | — | Highlights every occurrence, not just the first one. |
matches | readonly MatchRange[] | undefined | — | Ready match ranges [start, end]. They take precedence over query. |
opacity | string | number | undefined | — | Opacity of the highlight background (the --cds-highlight-opacity CSS variable). |
query | string | string[] | undefined | — | Search query: a string or an array of term strings. |
tag | string | JSXComponent<any> | undefined | 'span' | Custom HTML tag or component to render |
text | string | undefined | '' | The text the highlighting is performed in. |