Press "Enter" to skip to content

Creating react-highlighter component

vpandzic 0

If you were creating your own autocomplete in jQuery, React or any other library/framework you probably wanted to highlight some letters of each item that matches user search criteria something like this:

react-highlighter-component Creating react-highlighter component

In this article I will explain idea, and also solution that has only few lines of code. When I tried to do this few years ago it took me more than 150 lines of code. Here I will explain how to create it using React and TypeScript.

If you want to do this only by CSS, well, it is not possible. Idea is to take text of some item and split it into multiple HTML tags and apply CSS class only to certain HTML elements.

If original item was

 

and user types in kar newly created html would look like this:

If you know how JavaScript split function works you know that will not help in creating most elegant solution if you send to it just string delimiter. Problem is that when you try to split some string by another string it will not keep the separator.

Check this example:

The result of res will be an array with the values:

Parameters

separator Optional

Specifies the string which denotes the points at which each split should occur. The separator is treated as a string or as a regular expression. If a plain-text separator contains more than one character, that entire string must be found to represent a split point. If separator is omitted or does not occur in str, the array returned contains one element consisting of the entire string. If separator is an empty string, str is converted to an array of characters.

So javascipt split function can receive regular expression with specified search term. This is what I inially tried:

 

 

There were few problems. First I didn’t put search term in capturing group so I get same effect if I do:

Other problem is that I needed a way to ignore casing. Luckily RegExp as second parameter accepts flag “i” that basicly means ignore casing.

Combining those two this is I came up with:

 

This is whole render function of the component:

 

 

    Leave a Reply

    Your email address will not be published. Required fields are marked *