I receive html string from backend. I'm parsing html string using react-html-parser. But the package's import size is 174kb
. I can do the same thing using innerHTML
. Please refer to code below. I'm setting innerHTML in useEffect so that changes are reflected when text
changes.
- Using innerHTML
useEffect(() => {
document.getElementById(`text-${_id}`).innerHTML = text;
}, [text]);
- using parser (I can do it in return statement itself)
function SomeComponent({_id}) {
return (
<div className="list-group-item mb-3">
<div id={`text-${_id}`}>
{parser(text)}
</div>
</div>
)}
I looked at the import size using importCost
extension. Acc. to you, Which method will be faster. Is it worth using html-react-parser
?
CodePudding user response:
React is a JavaScript library and it internally uses JavaScript so, it will be slower.
If it's just about setting an html value, you can use .innerHTML
, but there are security considerations for its usage.
To avoid injection attacks(like XSS), we should sanitize the html while insertion(even if the DB is storing sanitized html).
Use a sanitizer like sanitize-html
or react-sanitize-html
like this
import SanitizedHTML from 'react-sanitized-html';
function SomeComponent({_id}) {
return (
<div className="list-group-item mb-3">
<div id={`text-${_id}`}
<SanitizedHTML html={ text} />
</div>
</div>
)}
html-to-react
parser (which internally calls html-to-dom-parser
) is react
specific and serves a different purpose. If you look at it's signature,
/**
* Converts HTML string to React elements.
*
* @param {string} html - HTML string.
* @param {object} [options] - Parser options.
* @param {object} [options.htmlparser2] - htmlparser2 options.
* @param {object} [options.library] - Library for React, Preact, etc.
* @param {Function} [options.replace] - Replace method.
* @returns {JSX.Element|JSX.Element[]|string} - React element(s), empty array, or string.
*/
function HTMLReactParser(html, options)
you can see that it returns React element(s), empty array, or string
Please note that Element.innerHTML
is not DOM parsing. Its different. AS per MDN Docs,
The Element property innerHTML gets or sets the HTML or XML markup contained within the element.