Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

html-parser-react-lison

lisonyang21MIT0.13.2TypeScript support: included

HTML to React parser.

html-react-parser, html, react, parser, dom

readme

html-react-parser

NPM

NPM version Build Status Coverage Status Dependency status NPM downloads Financial Contributors on Open Collective

HTML to React parser that works on both the server (Node.js) and the client (browser):

HTMLReactParser(string[, options])

It converts an HTML string to one or more React elements. There's also an option to replace an element with your own.

Example:

var parse = require('html-react-parser');
parse('<div>text</div>'); // equivalent to `React.createElement('div', {}, 'text')`

CodeSandbox | JSFiddle | Repl.it | Examples

Installation

NPM:

$ npm install html-react-parser --save

Yarn:

$ yarn add html-react-parser

CDN:

<!-- HTMLReactParser depends on React -->
<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/html-react-parser@latest/dist/html-react-parser.min.js"></script>
<script>
  window.HTMLReactParser(/* string */);
</script>

Usage

Import the module:

// ES Modules
import parse from 'html-react-parser';

// CommonJS
const parse = require('html-react-parser');

Parse single element:

parse('<h1>single</h1>');

Parse multiple elements:

parse('<li>Item 1</li><li>Item 2</li>');

Since adjacent elements are parsed as an array, make sure to render them under a parent node:

<ul>
  {parse(`
    <li>Item 1</li>
    <li>Item 2</li>
  `)}
</ul>

Parse nested elements:

parse('<body><p>Lorem ipsum</p></body>');

Parse element with attributes:

parse(
  '<hr id="foo" class="bar" data-attr="baz" custom="qux" style="top:42px;">'
);

Options

replace(domNode)

The replace callback allows you to swap an element with another React element.

The first argument is an object with the same output as htmlparser2's domhandler:

parse('<br>', {
  replace: function (domNode) {
    console.dir(domNode, { depth: null });
  }
});

Console output:

{ type: 'tag',
  name: 'br',
  attribs: {},
  children: [],
  next: null,
  prev: null,
  parent: null }

The element is replaced only if a valid React element is returned:

parse('<p id="replace">text</p>', {
  replace: domNode => {
    if (domNode.attribs && domNode.attribs.id === 'replace') {
      return React.createElement('span', {}, 'replaced');
    }
  }
});

Here's an example that modifies an element but keeps the children:

import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import parse, { domToReact } from 'html-react-parser';

const html = `
  <p id="main">
    <span class="prettify">
      keep me and make me pretty!
    </span>
  </p>
`;

const options = {
  replace: ({ attribs, children }) => {
    if (!attribs) return;

    if (attribs.id === 'main') {
      return <h1 style={{ fontSize: 42 }}>{domToReact(children, options)}</h1>;
    }

    if (attribs.class === 'prettify') {
      return (
        <span style={{ color: 'hotpink' }}>
          {domToReact(children, options)}
        </span>
      );
    }
  }
};

console.log(renderToStaticMarkup(parse(html, options)));

Output:

<h1 style="font-size:42px">
  <span style="color:hotpink">
    keep me and make me pretty!
  </span>
</h1>

Here's an example that excludes an element:

parse('<p><br id="remove"></p>', {
  replace: ({ attribs }) => attribs && attribs.id === 'remove' && <Fragment />
});

library

The library option allows you to specify which component library is used to create elements. React is used by default if this option is not specified.

Here's an example showing how to use Preact:

parse('<br>', {
  library: require('preact')
});

Or, using a custom library:

parse('<br>', {
  library: {
    cloneElement: () => {
      /* ... */
    },
    createElement: () => {
      /* ... */
    },
    isValidElement: () => {
      /* ... */
    }
  }
});

htmlparser2

This library passes the following options to htmlparser2 on the server-side:

{
  decodeEntities: true,
  lowerCaseAttributeNames: false
}

By passing your own options, the default library options will be replaced (not merged).

As a result, to enable decodeEntities and xmlMode, you need to do the following:

parse('<p /><p />', {
  htmlparser2: {
    decodeEntities: true,
    xmlMode: true
  }
});

See htmlparser2 options.

Warning: By overriding htmlparser2 options, there's a chance of breaking universal rendering. Do this at your own risk.

trim

Normally, whitespace is preserved:

parse('<br>\n'); // [React.createElement('br'), '\n']

By enabling the trim option, whitespace text nodes will be skipped:

parse('<br>\n', { trim: true }); // React.createElement('br')

This addresses the warning:

Warning: validateDOMNesting(...): Whitespace text nodes cannot appear as a child of <table>. Make sure you don't have any extra whitespace between tags on each line of your source code.

However, this option may strip out intentional whitespace:

parse('<p> </p>', { trim: true }); // React.createElement('p')

FAQ

Is this library XSS safe?

No, this library is not XSS (cross-site scripting) safe. See #94.

Does this library sanitize invalid HTML?

No, this library does not perform HTML sanitization. See #124, #125, and #141.

Are <script> tags parsed?

Although <script> tags and their contents are rendered on the server-side, they're not evaluated on the client-side. See #98.

Why aren't my HTML attributes getting called?

This is because inline event handlers like onclick are parsed as a string instead of a function. See #73.

The parser throws an error.

Check if your arguments are valid. Also, see "Does this library sanitize invalid HTML?".

Does this library support SSR?

Yes, this library supports server-side rendering on Node.js. See demo.

Why are my elements nested incorrectly?

Make sure your HTML markup is valid. The HTML to DOM parsing will be affected if you're using self-closing syntax (/>) on non-void elements:

parse('<div /><div />'); // returns single element instead of array of elements

See #158.

I get "Warning: validateDOMNesting(...): Whitespace text nodes cannot appear as a child of table."

Enable the trim option. See #155.

Don't change case of tags.

Tags are lowercased by default. To prevent that from happening, pass the htmlparser2 option:

const options = {
  htmlparser2: {
    lowerCaseTags: false
  }
};
parse('<CustomElement>', options); // React.createElement('CustomElement')

Warning: By preserving case-sensitivity of the tags, you may get rendering warnings like:

Warning: <CustomElement> is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements.

See #62 and example.

Benchmarks

$ npm run test:benchmark

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)

Contributors

Code Contributors

This project exists thanks to all the people who contribute. [Contribute].

Code Contributors

Financial Contributors

Become a financial contributor and help us sustain our community. [Contribute]

Individuals

Financial Contributors - Individuals

Organizations

Support this project with your organization. Your logo will show up here with a link to your website. [Contribute]

Financial Contributors - Organization 0 Financial Contributors - Organization 1 Financial Contributors - Organization 2 Financial Contributors - Organization 3 Financial Contributors - Organization 4 Financial Contributors - Organization 5 Financial Contributors - Organization 6 Financial Contributors - Organization 7 Financial Contributors - Organization 8 Financial Contributors - Organization 9

Support

License

MIT

changelog

Change Log

All notable changes to this project will be documented in this file. See standard-version for commit guidelines.

0.13.0 (2020-06-07)

Features

  • dom-to-react: add option trim that skips whitespace nodes (413eaa0)
  • index: type trim in HTMLReactParserOptions (be71b13)

0.12.0 (2020-06-04)

Features

  • index: add htmlparser2 type to HTMLReactParserOptions (81f74fb)
  • index: add options.htmlparser2 (c4ecf64)

0.11.1 (2020-06-03)

Performance Improvements

  • index: return empty array if first argument is empty string (7f61f97)

0.11.0 (2020-06-02)

Features

0.10.5 (2020-05-26)

Tests

  • html-to-react: tidy and organize tests in html-to-react.js (8dfbfe0)

Build System

  • package: add missing peerDependency typescript (91fb693)
  • package: upgrade devDependencies (b2dc83b)
  • rollup: upgrade rollup, consolidate config, remove cross-env (55b2b4e)

0.10.4 (2020-05-25)

Tests

  • attributes-to-props: test that CSS comment is not parsed (0c27987)
  • dom-to-react: tidy tests and add case for single node replace (452f6be)
  • tidy tests, replace assert.equal with assert.strictEqual (ef04eff)

0.10.3 (2020-03-28)

Bug Fixes

  • update .d.ts docstrings (bae05c0)
  • use JSX.Element for type definitions (d8e2ada)

0.10.2 (2020-03-13)

Bug Fixes

  • index: add default export for parser (6259959)

Tests

  • html-to-react: add test to ensure default export for parser (efba1d4)
  • html-to-react: have a stronger assert (064f0df)

0.10.1 (2020-02-08)

Bug Fixes

  • index: make replace property optional in index.d.ts (801512b), closes #134

0.10.0 (2019-11-09)

Build System

Features

  • dom-to-react: support Preact (c3e77bb)

Tests

  • types: move TypeScript tests from lint to test directory (7c9ab9d)

0.9.2 (2019-11-04)

Bug Fixes

  • refactor TypeScript declaration file for index.d.ts (f1fc00b)

Build System

0.9.1 (2019-07-09)

Build System

  • replace webpack with rollup in order to optimize bundle (a04ef27)
  • index: fix rollup error of mixing named and default exports (230de70)

0.9.0 (2019-07-09)

Bug Fixes

  • attributes-to-props: handle attr named after Object properties (3f857bb)

Build System

  • package: update react-property to 1.0.1 (26ebef9)

Features

  • attributes-to-props: check for overloaded boolean values (1151cfb)
  • attributes-to-props: replace react-dom with react-property (d6274b9), closes #107

Tests

  • attributes-to-props: improve test names (17fbdfd)

0.8.1 (2019-07-03)

Tests

  • html-to-react: update variable name to fix test (73237dd)

0.8.0 (2019-06-24)

Bug Fixes

  • attributes-to-props: fix lint error no-prototype-builtins (fa66dfc)

Build System

  • package: refactor webpack config and generate sourcemap (5dd4f07)
  • package: rename npm script cover to test:cover (7d806c8)
  • package: update `html-dom-parser@0.2.2` and devDependencies (b39ac53)
  • package: update dependencies and devDependencies (8765ea9)
  • package: update dependency style-to-object to 0.2.3 (c2cc2ec)

Features

  • dom-to-react: skip and do not parse <script> content (1fb5ee2)

Tests

  • html-to-react: add test that verifies domToReact is exported (320c364)
  • verify invalid style for attributesToProps throws an error (b97f2e1)

0.7.1 (2019-05-27)

0.7.0 (2019-04-05)

Bug Fixes

  • coveralls: moved dtslint tests to lint folder (306fceb)
  • types: html-dom-parser > html-react-parser (438b9af)

Features

  • types: add lib/dom-to-react declaration (27ed8b6)

0.6.4 (2019-03-29)

Bug Fixes

  • dom-to-react: allow custom keys for replacement (abf20a2)
  • dom-to-react: fix typos in the test (4eec53e)

0.6.3 (2019-03-19)

Bug Fixes

  • typescript: test.tsx after dtslint run (38e6bba)

0.6.2 (2019-03-07)

0.6.1 (2019-01-03)

Bug Fixes

  • utilities: allow numbers in custom style names (5a6600f)

0.6.0 (2018-12-17)

Features

  • utilities: add support for custom styles beginning with "--*" (2c0a9dc)

0.5.0 (2018-12-16)

Bug Fixes

  • attributes-to-props: undo default function parameter (1017b25)

Features

  • support custom elements in React 16 (7b2c5a8)

0.4.7 (2018-09-14)

0.4.6 (2018-05-13)

Bug Fixes

  • accidentally left a console (953e564)
  • added test case for viewBox (261ffb7)
  • moving svg mock to correct place (6ffb148)
  • svg attributes now correctly handled (94643e1)

0.4.5 (2018-05-09)

Bug Fixes

0.4.4 (2018-05-07)

Bug Fixes

0.4.3 (2018-03-27)

Bug Fixes

  • parser: fix boolean attributes parsing (e478a44)
  • parser: fix case when style is empty string (fa2a8b4)

0.4.2 (2018-02-20)

Bug Fixes

0.4.1 (2017-11-28)

Bug Fixes

  • attributes-to-props.js: Remove unappropriate console logging and remove double quote from tests (10ff149)
  • attributes-to-props.js: Use AST to transform style attributes into an style object (68cd565)
  • utilities.js: Format string to lowercase before converting to camel case and assert the string is a string (4522666)

0.4.0 (2017-10-01)

Added

  • react-dom-core to dependencies (closes #43)
    • react-dom 16 no longer exposes lib, which includes the DOM property configs
    • Upgrade devDependencies of react and react-dom to 16
    • Update README and examples

0.3.6 (2017-09-30)

Changed

  • Dependencies
    • html-dom-parser@0.1.2
      • Fixes IE9 client parser bug
    • Set react and react-dom versions to ^15.4
      • Version 16 no longer exposes HTMLDOMPropertyConfig and SVGDOMPropertyConfig

0.3.5 (2017-06-26)

Changed

0.3.4 (2017-06-17)

Changed

Removed

  • Dependencies:
    • jsdomify

0.3.3 (2017-01-27)

Added

  • Created CHANGELOG with details on each version release (#37)

Changed

  • Update examples to load parser from relative dist/ directory (#36)
  • Removed unnecessary field "browser" in package.json (#36)

0.3.2 (2017-01-26)

Fixed

  • Decode HTML entities by default on node (#34)

0.3.1 (2017-01-10)

Changed

  • Updated README by fixing CDN installation instructions and adding JSFiddle

0.3.0 (2016-11-18)

Changed

  • Upgrade react and react-dom to >15.4

0.2.0 (2016-11-18)

Added

  • Create npm script clean that removes dist/ directory

Fixed

  • Silence webpack warning by keeping react <15.4 in this version

0.1.1 (2016-11-17)

Fixed

  • HTMLDOMPropertyConfig.js and SVGDOMPropertyConfig.js have been moved from react/lib/ to react-dom/lib/ in v15.4

0.1.0 (2016-10-14)

Changed

  • Replace HTML to DOM converter with html-dom-parser (#28)
    • Save html-dom-parser
    • Remove domhandler and htmlparser2
  • Update tests and README

0.0.7 (2016-09-27)

Added

  • Examples of using the parser with script tag and RequireJS (#26)

Changed

  • Update build (#25)
  • Update README description, instructions, and examples (#27)

0.0.6 (2016-09-27)

Added

  • README example with advanced usage of replace option from @poacher2k (#17)
  • Contributors section to README (#21)

Changed

  • Use webpack to build UMD bundle (#22)

Fixed

  • Regex bug on client parser (#24)

0.0.5 (2016-08-30)

Changed

  • Remove key parameter from replace and use React.cloneElement (#18)

Fixed

  • Parsing of <script> and <style> tags (#20)

0.0.4 (2016-08-29)

Added

  • Send coverage report generated by istanbul to coveralls (#12)
  • Display badges in README (#13, #15)
  • Update parser's replace option with additional 2nd parameter key (#16)

Fixed

  • Void elements (e.g., <img />) should not have children (#16)
  • Set default key parameter for sibling elements due to keys warning (#16)

0.0.3 (2016-08-24)

Added

  • Make package UMD compatible (#9)
  • Throw an error if first argument is not a string (#10)

Changed

  • Differentiate between node and browser environments for parser (#5)

Fixed

  • HTML to DOM conversion on the client (#10)

0.0.2 (2016-08-23)

Added

Fixed

  • package.json peerDependencies for react and react-dom

0.0.1 (2016-08-23)

Added

  • HTML to React parser which consists of:
    • HTML string to DOM object converter
    • DOM object to React nodes converter
  • Tests
  • README