How to render Html in react-native and alter the data?

Viewed 2233

I want to alter the content of the html coming from the api.

I will use some example html in this case

const htmlContent = `
    <h1>This HTML snippet is now rendered with native components !</h1>
    <h2>Enjoy a webview-free and blazing fast application</h2>
    <img src="https://i.imgur.com/dHLmxfO.jpg?2" />
    <em style="textAlign: center;">Look at how happy this native cat is</em>
`;

Here is the example html. What I want to do is i want to replace the the word Enjoy with Do Not Enjoy and display them when the component is rendered.

The package I am using is called React-native-render-html to render the html.

This is how i rendered the html

export default function Demo() {
  const contentWidth = useWindowDimensions().width;
  return (
    <ScrollView style={{ flex: 1 }}>
      <HTML source={{ html: htmlContent }} contentWidth={contentWidth} />
    </ScrollView>
  );
}

There is a documentation in there stated that we can use these code to alter the data but I don't know how to use them for my specific case. Can some one help?

// ... your props
alterData: (node) => {
  let { parent, data } = node;
  if (parent && parent.name === "h1") {
    return data.toUpperCase();
  }
};
1 Answers

In the alterData method, you get the content html as data. You can modify this to match your needs.

In your case, we can use the replace method to replace all instances of "Enjoy" to "Do not Enjoy".

<HTML
  source={{ html: htmlContent }}
  contentWidth={contentWidth}
  alterData={(node) => {
    let { parent, data } = node;
      return data.replace("Enjoy", "Do not Enjoy");
  }}
/>

If you want, you can use the parent parameter to determine which tags to update or skip.

Related