Skip to content

Instantly share code, notes, and snippets.

@nathanharper
Last active June 18, 2018 14:24
Show Gist options
  • Save nathanharper/c8c7a0c6a107dcd74acfa9bbe8bb10f0 to your computer and use it in GitHub Desktop.
Save nathanharper/c8c7a0c6a107dcd74acfa9bbe8bb10f0 to your computer and use it in GitHub Desktop.
React component to output Raw HTML without using dangerouslySetInnerHTMLOMGWhyAreYouDoingThisPleaseStop
import React from 'react';
/**
* Helper component for injecting raw html into the page.
*/
const rawFactory = type =>
class RawComponent extends React.Component {
render() {
const { children: strings, ...props } = this.props;
// if there are any spaces inside the JSX tag, they will get passed in as extra children.
// Join all the children together into one string.
const __html = strings.join('');
return React.createElement(type, {
dangerouslySetInnerHTML: { __html },
...props,
});
}
};
const Raw = new Proxy(
{},
{
get: (target, prop) => {
if (target[prop] == null) {
target[prop] = rawFactory(prop);
}
return target[prop];
},
}
);
export default Raw;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment