Closed MKorostoff closed 4 years ago
I pulled this from an open PR for an example:
const transform = (node) => {
if (node.name === 'a') {
node.attribs.target = '_blank';
return convertNodeToElement(node);
}
};
@chadwilken sorry, I don't really understand what point you're trying to make there.
Basically that you may need to control some aspects of the HTML. It allows you to override attributes such as using a different target so users don't leave your app. In general I don't think you need this unless you want to customize output.
@chadwilken ah, I think I see what you're saying. Would you mind providing a slightly fuller example with a little more context so I can see how/where one would use this transform()
method you showed above?
We create a custom component that wraps this lib to make sure than anywhere we render HTML it will always open links in a new tab. You could do this for a bunch of different things though such as adding utm
s or other data attributes for analytics libraries.
import ReactHtmlParser, { convertNodeToElement } from 'react-html-parser';
const transform = (node) => {
if (node.name === 'a') {
node.attribs.target = '_blank';
return convertNodeToElement(node);
}
};
const RichText = (html) => {
return ReactHtmlParser(html, { transform });
};
export default RichText;
Ah, makes sense. Thanks!
Opening in a new tab won't necessarily make it secure. You would also need rel="noreferrer noopener"
.
https://web.dev/external-anchors-use-rel-noopener/
Does this package also prevent <script>
tags from being rendered?
Not trying to be snarky here, but I genuinely don't understand what problem this library is meant to solve, that's not equally solved with dangerouslySetInnerHTML. Does it provide some benefit with regard to security or performance? Does it offer some special functionality? The readme just says this avoids use of dangerouslySetInnerHTML, but it's not clear to me why that's desirable.