React js parse with content between html strips

31 Views Asked by At

please, is there any way to parse without errors a content that contains html tags and some text inside strips < and >.

I've tried:


import DOMPurify from 'dompurify';
import parse from 'html-react-parser';

const htmlString = '<p>test<br/><img src="....." />... <[email protected]></p>';
const cleanedHTML = DOMPurify.sanitize(htmlString);

<td>{parse(cleanedHTML)}</td>

It works fine But it removes the content [email protected] ( THIS IS JUST AN EXAMPLE OF WHAT CAN BE BETWEEN STRIPS), and when I dont use dompurify.santitize I got errors: Uncaught DOMException: String contains an invalid character.

1

There are 1 best solutions below

1
Hamude Shahin On

Try to use helper libs; dompurify, and html-react-parser

here is an example of how you can use those libs:

import React from 'react';
import DOMPurify from 'dompurify';
import parse from 'html-react-parser';

const MyComponent = () => {
  const htmlString = '<p>test<br/><img src="....." />... <[email protected]></p>';
  // Sanitize the HTML string to remove potentially unsafe elements and attributes
  const cleanedHTML = DOMPurify.sanitize(htmlString);

  const customParse = (html) => {
    const strippedTags = ['emailtouser'];
    return parse(html, {
      replace: (domNode) => {
        if (domNode.type === 'tag' && strippedTags.includes(domNode.name)) {
          return null; // Remove the specified tags
        }
      },
    });
  };

  return <td>{customParse(cleanedHTML)}</td>;
};

export default MyComponent;