How to replace parts of a string with a component?
Problem
We want to take normal text and somehow replace some parts of the text with React Component(s). As I didn’t want to use any 3rd party library I broke the problem into small problems and came up with this solution
Solution
constreplaceJSX=(text: string |null,find: string[],jsx: React.ReactElement[])=>{if(text ===null)returnnullletresult:(| string
| React.ReactElement<any, string | React.JSXElementConstructor<any>>)[]= text.replaceAll("{","").replaceAll("}","").split(/\b/)// split on word boundaries
find.forEach((findWord, findIndex)=>{
result = result.map(word=>{if(findWord === word){return jsx[findIndex]}return word
})})return result
}
Explanation
First spilt the words on word boundaries. If we spilt on word boundaries we can keep the spaces and newline character etc.
Loop over the words to be replaced and then replace them with your React Component in that very same Array.
Pass this Array to React and watch react render out your text with components into the desired output.