How to replace parts of a string with a component?


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


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 = => {
      if (findWord === word) {
        return jsx[findIndex]
      return word
  return result


  • 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