Gh05d
Gh05d

Reputation: 9002

Replace Text node with React Element via react-native-render-html in React Native

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?

Upvotes: 1

Views: 539

Answers (0)

Related Questions