How to remove tags from react-native-render-html?

Viewed 855

How do I remove h2 tags that has only <br> tag?

<h2><br></h2>

1 Answers

You can use alterChildren prop to delete some DOM nodes:

const html = `
<body>
<h2>Hello world</h2>
<p>Lorem ipsum</p>
<h2><br></h2>
</body>
`;

function hasOnlyBrChildren(node) {
  return node.children.every(
    (child) => child.type === 'tag' && child.name === 'br'
  );
}

function alterChildren(node) {
  return node.children.filter(
    (child) =>
      child.type !== 'tag' ||
      !(child.name === 'h2' && hasOnlyBrChildren(child))
  );
}

export default function App() {
  return (
    <ScrollView>
      <HTML alterChildren={alterChildren} html={html} />
    </ScrollView>
  );
}

I made a snack here (I just replaced br with div to visually assess the effectiveness of the function): https://snack.expo.io/@jsamr/rnrhtml-alter-children

Related