Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

193
Views
Highlight characters in a String in React

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

<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>
about 4 years ago · Juan Pablo Isaza Report

0

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)}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!