React: Is there any more efficent way other than using dangerouslySetInnerHTML to set svg string?

Created on 27 Aug 2018  Â·  6Comments  Â·  Source: facebook/react

When I'm parsing markdown text, I will have a string whose content is a svg file, such as

<svg height="100" width="100">
<circle 
    cx="50" cy="50" r="40" 
    stroke="black" stroke-width="3" fill="red" />
</svg>

As far as now, it seems that the only way to render this svg string is to use dangerouslySetInnerHTML, I wanna to ask:

  1. Will this way inefficent?
  2. Is there any more efficent way in React?

Thanks for reading this issue.
Looking forward your awesome answers.

Most helpful comment

Shipping HTML parser to the client just to parse a pre-generated SVG seems excessive and would create a performance issue — unless you do it at compile time.

All 6 comments

There are no performance problems with doing this. But be careful to make sure the HTML string is coming from a trusted source since otherwise it will create a security issue.

You can also use a HTML parser to avoid using dangerouslySetInnerHTML.

https://www.npmjs.com/package/react-html-parser

Shipping HTML parser to the client just to parse a pre-generated SVG seems excessive and would create a performance issue — unless you do it at compile time.

@gaearon Yep, very valid point.

@gaearon, How about adding DOMPurify to sanitise the HTML before inserting it in the DOM via dangerouslySetInnerHTML

@ramsunvtech Unless there's a compelling reason to do so, I think it'd be an overkill to do DOMPurify in the browser.

Was this page helpful?
0 / 5 - 0 ratings