html-react-parser

repository·master·Indexed 25 days ago

https://github.com/remarkablemark/html-react-parser

A utility that converts HTML strings into React elements, compatible with both Node.js and browser environments. It provides features to replace or transform elements using the replace and transform options, convert DOM attributes to React props via attributesToProps, and supports custom UI libraries like Preact. Version 6.1.5.

Tokens
5.5K
Snippets
22
Records
39
Agent score
81%

What's inside html-react-parser

  1. Install html-react-parser

    master

    You can install html-react-parser using npm, yarn, or via CDN.

    NPM:

    npm install html-react-parser --save

    Yarn:

    yarn add html-react-parser

    CDN: Note that html-react-parser depends on React. Ensure React is loaded before the parser.

    <!-- HTMLReactParser depends on React -->
    <script src="https://unpkg.com/react@18/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>
    npm install html-react-parser --save
  2. Basic Usage of parse()

    master

    The parse function converts an HTML string into one or more React elements. It works on both the server (Node.js) and the client (browser).

    Importing:

    ES module:

    import parse from 'html-react-parser';

    CommonJS:

    const parse = require('html-react-parser').default;

    Parsing Examples:

    Single element:

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

    Multiple adjacent elements (ensure you render them under a parent element in React):

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

    Nested elements:

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

    Element with attributes:

    parse('<hr id="foo" class="bar" data-attr="baz" custom="qux" style="top:42px;">');
    import parse from 'html-react-parser';
    
    parse('<p>Hello, World!</p>'); // React.createElement('p', {}, 'Hello, World!')
  3. Migrate to v5

    master

    When upgrading to version 5, note the following changes:

    • The project migrated to TypeScript.
    • CommonJS imports now require the .default key:
    const parse = require('html-react-parser').default;

    If you encounter the error Argument of type 'ChildNode[]' is not assignable to parameter of type 'DOMNode[]', use a type assertion:

    domToReact(domNode.children as DOMNode[], options);
  4. Add React-specific ESLint rules

    master

    To enforce React-specific best practices, you can install and configure eslint-plugin-react-x and eslint-plugin-react-dom. This requires setting up the languageOptions.parserOptions with your project's tsconfig files.

    // eslint.config.js
    import reactX from 'eslint-plugin-react-x';
    import reactDom from 'eslint-plugin-react-dom';
    
    export default defineConfig([
      globalIgnores(['dist']),
      {
        files: ['**/*.{ts,tsx}'],
        extends: [
          // Enable lint rules for React
          reactX.configs['recommended-typescript'],
          // Enable lint rules for React DOM
          reactDom.configs.recommended,
        ],
        languageOptions: {
          parserOptions: {
            project: ['./tsconfig.node.json', './tsconfig.app.json'],
            tsconfigRootDir: import.meta.dirname,
          },
        },
      },
    ]);
  5. Enable type-aware ESLint rules in Vite

    master

    For production applications, it is recommended to enable type-aware lint rules by replacing tseslint.configs.recommended with more specific configurations in your ESLint config. You must also configure parserOptions to point to your tsconfig files.

    Available tseslint configurations:

    • tseslint.configs.recommendedTypeChecked
    • tseslint.configs.strictTypeChecked (stricter)
    • tseslint.configs.stylisticTypeChecked (stylistic rules)
    export default defineConfig([
      globalIgnores(['dist']),
      {
        files: ['**/*.{ts,tsx}'],
        extends: [
          // Remove tseslint.configs.recommended and replace with this
          tseslint.configs.recommendedTypeChecked,
          // Alternatively, use this for stricter rules
          tseslint.configs.strictTypeChecked,
          // Optionally, add this for stylistic rules
          tseslint.configs.stylisticTypeChecked,
        ],
        languageOptions: {
          parserOptions: {
            project: ['./tsconfig.node.json', './tsconfig.app.json'],
            tsconfigRootDir: import.meta.dirname,
          },
        },
      },
    ]);
  6. Configure htmlparser2 options

    master

    You can override default htmlparser2 options.

    Warning: htmlparser2 options do not work on the client-side (browser); they only work on the server-side (Node.js). Overriding these can break universal rendering.

    To enable xmlMode:

    parse('<p /><p />', {
      htmlparser2: {
        xmlMode: true,
      },
    });
    parse('<p /><p />', {
      htmlparser2: {
        xmlMode: true,
      },
    });
  7. Remove whitespace using the trim option

    master

    By default, whitespace is preserved. To remove whitespace, enable the trim option.

    // Default behavior (whitespace preserved)
    parse('<br>\n'); // [React.createElement('br'), '\n']
    
    // With trim enabled
    parse('<br>\n', { trim: true }); // React.createElement('br')

    Note: Enabling trim may strip out intentional whitespace, such as in <p> </p>.

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

    master

    By default, tags are lowercased during parsing. To preserve the case of tags (e.g., for <CustomElement>), pass the lowerCaseTags: false option within the htmlparser2 configuration object.

    Warning: Preserving case-sensitivity may trigger React rendering warnings if you use non-PascalCase for components or non-lowercase for standard HTML elements.

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