I have a text such as
"This is my text Albert is my special word"
also I have a react component called SpecialWord
I want to search through the text above and wrap all the special words in this case (Albert) with my SpecialWord
Component
so the text above will output to something like this
This is my text <SpecialWord>Albert</SpecialWord> is my special word
after that I want to render the final result as a react component so something like this if possible
<div dangerouslySetInnerHTML={{__html: finalResult}}></div>
I already tried to get the start and end index of the special word and wrapped it with native html elements, when rendered it works fine since they are native html elements but I can’t use the same approach with the SpecialWord
component since it’s not a native html elements
3
Answers
I solved the problem by some splitting and recombining if anyone were interested in the solution here's a sandbox https://codesandbox.io/s/amazing-surf-uor8sd?file=/src/pages/index.js
I would avoid using
dangerouslySetInnerHTML
.You can do something like:
A couple of notes:
map
over the words of the sentence and output a React component for the special word. I usedIntl.Segmenter
which is fairly new and might not be supported on older browsers. Also, you might want to match things like "special word".Intl.Segmenter
splits in words so you won’t be able to match multiple words.key={index}
, using an index as key is often a mistake. In this case it works because we don’t have a unique ID for each word.<SpecialWord word={part} />
(React children are kinda hard to work with)I hope this helps!
You can put your text in an array and use map to return the words wrapped with the correct wrapper, for example: