I wanna bold a specific part of a string in my react js app but the result is not true; This is my code and its returned:
data?.map((item) => (<li key={item.id}>{item.title.replace(new RegExp(value, 'g'), `<b>${value}</b>`)}</li>)) // rendered value: app<b>l</b>e
CodePudding user response:
Because you're returning a string, not a react element. That is to say, There's an important difference between app<b>l</b>e
(an array of react elements) and 'app<b>l</b>e'
(a string).
data?.map((item) => (
<li key={item.id}>
{
// spread to convert string to array
[...item.title].map((letter) =>
// if the letter matches, wrap in a <b/> tag
letter === value ? <b>{letter}</b> : letter)
}
</li>
))
https://codesandbox.io/s/pedantic-tree-r4egc?file=/src/App.js