1

Problem

I am using react-native-render-html to render some html in React Native. The problem is that this html contains some placeholders like {{{placeholder:items:0}}} which should be replaced with a React Element.

Code

I am using the onText function currently as outlined in this example:

  function onText(text) {
    const toReplace = text.data.match(gemstoneRegex);

    if (toReplace?.length) {
      let [placeholder] = toReplace;
      placeholder = placeholder.replace(/\{/g, "");
      placeholder = placeholder.replace(/\}/g, "");

      const [name, position] = placeholder.split(":items:");

      text.data =
        (
          <Gemstone
            stones={[gemstones[name]?.de[position]]}
            displayTitle={gemstones[name]?.de[0]?.displaytitle || name}
            fieldName={name}
          />
        ) || `${name} couldn't be replaced!`;
    }
  }

This would work fine for a simple text string, but unfortunately not for a React Element. Is there a way to do this? The onElement function seems to have utility methods to add and remove elements. Is that also possible for text nodes?

Gh05d
  • 7,923
  • 7
  • 33
  • 64
  • 1
    That will not work. `onText` works for DOM nodes, not React elements. What you can do: (1) In `onElement`, look for text children. When you find a text matching this regex, replace the text child with a custom element such as `` (2) [Register `gemstone` HTLM element.](https://meliorence.github.io/react-native-render-html/docs/guides/custom-renderers#example-registering-a-new-tag) (3) [Define a custom renderer for `gemstone`](https://meliorence.github.io/react-native-render-html/docs/guides/custom-renderers#minimal-example). – Jules Sam. Randolph Oct 21 '22 at 16:00

0 Answers0