Html-react-parser: How to deal with !important in style attributes?

Created on 18 Feb 2021  ·  8Comments  ·  Source: remarkablemark/html-react-parser

I have the unfortunate situation that I sometimes get html tags from a cms, which include inline styles with !important in them. I have to parse those and render them in a React app.

There is nothing I can do about that and all styles with !important attached to them get stripped out by React.
Is there some way I can use html-react-parser to keep those styles, so they will remain in the body?
Sorry if this isn't the right place to ask about this, feel free to close this issue in that case.

Thanks!

question

All 8 comments

@linkurzweg You might not need html-react-parser. See fiddle. Just be aware of XSS vulnerability if you use dangerouslySetInnerHTML.

@remarkablemark Ah, I didn't even think of dangerouslySetInnerHTML!
No real risk for XSS in my case, so that should be fine.

The problem is, I still need to run everything through html-react-parser, because the body can contain elements I need to replace with some React component. Only if the element has a style attribute I can render it as it is.
Is there any way I can convert the domNode back to a string when parsing?

Thank you very much!

@linkurzweg You can pass your domNode in domToReact() and it will render it as a React element. See replace examples.

@remarkablemark Thanks again! I know that, but I don't see how that would help in my case?
I still would need to get the domNode back to a string that I could use with dangerouslySetInnerHTML or am I not getting something?

@linkurzweg I don't follow your use-case. Can you provide an example using CodeSandbox, JSFiddle, or Repl.it?

@remarkablemark see fiddle here: https://jsfiddle.net/9bezs1rt/.
So, it's like this: I get one huge string with all the html in it, that needs to be parsed in some way (can contain script tags, iframes, social media embeds etc.). I need to iterate through all the dom nodes and handle a lot of different cases.

If the dom node has some inline styles attached to it, I can assume I don't need to replace it with some React component and I just want to pass it through, including styles that have !important. And unfortunately those get lost.

@linkurzweg Thank you for creating the fiddle. So the reason why the styles are not rendered correctly is because inline styles do not need !important.

After removing !important, I made the red border show. See updated fiddle.

@remarkablemark Of course, silly me! There can be some other style tags with !important inside the html string (it's all very messy) that might clash with the inline styles. But I can remove the !important there as well, so it should be fine. :D Thanks a lot for looking at this and your help!

Was this page helpful?
0 / 5 - 0 ratings