peternewnham / react-html-parser

Converts HTML strings directly into React components and provide a simple way to modify and replace the content.
https://peternewnham.github.io/react-html-parser
MIT License
781 stars 103 forks source link

Why? #69

Closed MKorostoff closed 4 years ago

MKorostoff commented 4 years ago

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.

chadwilken commented 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);
  }
};
MKorostoff commented 4 years ago

@chadwilken sorry, I don't really understand what point you're trying to make there.

chadwilken commented 4 years ago

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.

MKorostoff commented 4 years ago

@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?

chadwilken commented 4 years ago

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 utms 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;
MKorostoff commented 4 years ago

Ah, makes sense. Thanks!

samwalshnz commented 4 years ago

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/

samwalshnz commented 4 years ago

Does this package also prevent <script> tags from being rendered?