I'm trying to highlight a matched substring in a searchable array of strings. I'm pretty close I think, just that last bit is not working.
I display an array of strings. When I type in an input the substrings in the array are supposed to get highlighted (using <mark></mark>
) when matched with the input. The matching works ok but instead of highlighted text I get [object Object]
instead.
So this is the part of code in question (it sits in Jsx inside a .map()
method:
<div>
{item.matched.length > 0
? item.name.replace(new RegExp(inputText, 'gi'), (match) => (
<mark>{match}</mark>
))
: item.name}
</div>
The item
is an element of the array that I'm mapping and has two properties: name
& matched
. matched
is either empty or contains the typed search pattern if part or all of name
matches it.
And this is what I'm getting when typing into text box:
So clearly the search and match work correctly and look what I get: [object Object]
instead of highlighted search pattern.
I've tried to return a template string, like that backquote<mark>${match}</mark>
backquote, but that results in displaying <mark>a</mark>
in my example.
So I'm at loss here and any constructive feedback will be greatly appreciated.
CodePudding user response:
we should render at in html
<div dangerouslySetInnerHTML={{ __html: (item.matched.length > 0
? item.name.replace(new RegExp(inputText, 'gi'), (match) => {
return `<span>${match}</span>`
})
: item.name) }}>