Home > Software design >  Highlight characters in a String in React
Highlight characters in a String in React

Time:02-27

I am trying to build an autocomplete component where the relevant characters are highlighted in the search suggestions as the user types.

The way I have come up to highlight the characters is this JSX

{suggestion.substring(0, ind)  
                <mark>{suggestion.substring(ind, val.length)}</mark>  
                suggestion.substring(val.length, suggestion.length)}

but it renders an `[Object Object] instead of the string.

How can I correct this?

Here's my whole code

      searchSuggestions
        .filter((suggestion) => {
          const lowerSuggestion = suggestion.toLowerCase();
          const val = eventValue.toLowerCase();
          console.log("lowersuggestion is", lowerSuggestion, val);
          return lowerSuggestion.indexOf(val) > -1;
        })
        .map((suggestion) => {
          const lowerSuggestion = suggestion.toLowerCase();
          const val = eventValue.toLowerCase();
          const ind = lowerSuggestion.indexOf(val);
          console.log("ind is", ind, typeof suggestion);
          return (
            <div>
              {suggestion.substring(0, ind)  
                <mark>{suggestion.substring(ind, val.length)}</mark>  
                suggestion.substring(val.length, suggestion.length)}
            </div>
          );
        })

Assuming searchSuggestions is an array of string. How should I go about it?

CodePudding user response:

<mark is a JSX element - which is an object. When you interpolate it (or most objects) into a string, you'll get [object Object].

Use an array instead, so that it gets interpolated into the JSX, rather than interpolated into a string.

<div>
    {[
        suggestion.substring(0, ind),
        <mark>{suggestion.substring(ind, val.length)}</mark>,
        suggestion.substring(val.length, suggestion.length)
    ]}
</div>

CodePudding user response:

There was a problem with the JSX itself, I solved it by changing it to

{suggestion.substring(0, ind)}
              <mark style={{ backgroundColor: "#f7e7d0" }}>
                {suggestion.substring(ind, ind   val.length)}
              </mark>
              {suggestion.substring(ind   val.length, suggestion.length)}
  • Related