Last active
June 18, 2018 14:24
-
-
Save nathanharper/c8c7a0c6a107dcd74acfa9bbe8bb10f0 to your computer and use it in GitHub Desktop.
React component to output Raw HTML without using dangerouslySetInnerHTMLOMGWhyAreYouDoingThisPleaseStop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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