html-react-parser
An HTML to React parser that works on both the server and the browser:
HTMLReactParser(htmlString[, options])
Example:
CodeSandbox | JSFiddle | repl.it
Installation
NPM:
Yarn:
unpkg (CDN):
Usage
Given you have html-react-parser
imported:
Parse single element:
Parse multiple elements:
Because the parser returns an array for adjacent elements, make sure it's nested under a parent element when rendered:
Parse nested elements:
Parse element with attributes:
Options
replace(domNode)
The replace
method allows you to swap an element with your own React element.
The first argument is domNode
―an object with the same output as htmlparser2's domhandler.
The element is replaced only if a valid React element is returned.
The following example uses replace
to modify the children:
The output:
The following example uses replace
to exclude an element:
Testing
Benchmarks
Here's an example output of the benchmarks run on a MacBook Pro 2017:
html-to-react - Single x 415,186 ops/sec ±0.92% (85 runs sampled)
html-to-react - Multiple x 139,780 ops/sec ±2.32% (87 runs sampled)
html-to-react - Complex x 8,118 ops/sec ±2.99% (82 runs sampled)