html-react-parser icon indicating copy to clipboard operation
html-react-parser copied to clipboard

Ignore attribute when attribute content is invalid

Open shiglet opened this issue 6 years ago • 6 comments

html-react-parser is a great tool ! But unfortunately, i'm having an exception when i'm trying to parse html string that content invalid attribute, so my app is crashing : undefined:1:2: property missing ':'. I can of course try that exception to avoid the app to crash but it won't really solve my issue.

I'm aware that's not to html-react-parser fault, but i would like to know if it's possible with html-react-parser to ignore some attribute when they are invalid, in my case i'm having troubles with an invalid style attribute. Its content isn't valid. If not, do you have any other idea to achieve that ?

Thank you !

shiglet avatar Mar 03 '20 13:03 shiglet

This sounds like invalid CSS in your HTML. See 'The parser throws an error'.

remarkablemark avatar Mar 04 '20 01:03 remarkablemark

This is related to #125

remarkablemark avatar Mar 04 '20 01:03 remarkablemark

Hello,

Thank you for your answer. I had already seen this issues. Unfortunately, i can't use sanitize-html, the reason is that i need to keep valid styling, and remove them only when it's invalid.

Is there any way to remove that with sanitize-html or another library ? I don't really know how can i actually know in javascript if the given style is actually valid or not. I know it's not related to html-react-parser, but i could actually use the html-react-parser replace method to remove that style attribute as long as i know how to be sure that the style is valid or not.

EDIT: Maybe should i need to edit (in local) the inline-style-parser to return null instead of throwing that "missing ':'" error when the attribute content isn't valid ?

Thank you.

shiglet avatar Mar 04 '20 06:03 shiglet

Since the library uses style-to-object under the hood (to parse inline style attribute into an object), you can wrap the style parsing in a try-catch:

const parse = require('html-react-parser');
const { domToReact } = parse;
const style = require('style-to-object');

parse('<hr style="/*">', {
  replace: domNode => {
    if (domNode.attribs && domNode.attribs.style) {
      try {
        style(domNode.attribs.style);
      } catch (error) {
        // delete the attribute that's causing the error
        // then convert the dom node to react
        delete domNode.attribs.style;
        return domToReact(domNode);
      }
    }
  },
});

See Repl.it example.

remarkablemark avatar Mar 10 '20 02:03 remarkablemark

Thank you @remarkablemark . I also struggle with this issue for quite a long time. Very appreciate for the solution!

ZigZagT avatar Mar 21 '20 16:03 ZigZagT

You're very welcome

remarkablemark avatar Mar 21 '20 17:03 remarkablemark