How to replace parts of a string with a component?

Problem

notion image
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

const replaceJSX = (
  text: string | null,
  find: string[],
  jsx: React.ReactElement[]
) => {
  if (text === null) return null

  let result: (
    | 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.
notion image
  • Loop over the words to be replaced and then replace them with your React Component in that very same Array.
notion image
  • Pass this Array to React and watch react render out your text with components into the desired output.
 

Code Sandbox