HTML2React
A utility for turning raw HTML into React elements.
Installation
npm install --save html2react
Usage
Basic HTML conversion
If you want to take raw HTML, SVG or any arbitrary XML and turn it into something that you can use in a React application, without using dangerouslySetInnerHTML, then you can simply pass it to html2react
:
const html = ` <h1>Foo</h1> <p><a href="#" style="text-decoration: none;">Bar</a></p> <p>Baz</p>`
Note: All attributes but event handlers will be transferred to the React elements.
HTML conversion with element overrides
A powerful feature of html2react
is the ability to target elements in the provided HTML and override them with React components, using nothing but CSS selectors for the mapping. Super simple!
The following example maps any <a>
tag in the HTML to the local Link
component:
{ return <a ...props style= textDecoration: 'none' />} const html = ` <h1>Foo</h1> <p><a href="#">Bar</a></p> <p>Baz</p>`const content =
The following example maps any <a>
tag with an external
class to the local ExternalLink
component. It also demonstrates a slightly more complex selector that maps only the third <p>
tag to a <p>
tag that wraps the local Link
component:
{ return <a ...props style= textDecoration: 'none' />} { return <Link ...props target='_blank' />} const html = ` <h1>Foo</h1> <p><a href="http://bar" class="external">Bar</a></p> <p><a href="#">Baz</a></p> <p>Qux</p>`const content =
License
MIT (http://www.opensource.org/licenses/mit-license.php)
See LICENSE attached.