html-react-parser
repository·master·Indexed 25 days ago
https://github.com/remarkablemark/html-react-parserA 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.
What's inside html-react-parser
- This library is not XSS (cross-site scripting) safe and does not sanitize HTML. To mitigate security risks, you should enforce a Content Security Policy (CSP) using Trusted Types.
Install html-react-parser
masterYou can install
html-react-parserusing npm, yarn, or via CDN.NPM:
npm install html-react-parser --saveYarn:
yarn add html-react-parserCDN: Note that
html-react-parserdepends 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 --saveBasic Usage of parse()
masterThe
parsefunction 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!')Migrate to v5
masterWhen upgrading to version 5, note the following changes:
- The project migrated to TypeScript.
- CommonJS imports now require the
.defaultkey:
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);Migrate to v6
masterWhen upgrading to version 6, note the following changes:
- The build target changed from
es5toes2016. html-dom-parserwas upgraded tov7.domhandlerwas upgraded tov6.
- The build target changed from
Add React-specific ESLint rules
masterTo enforce React-specific best practices, you can install and configure
eslint-plugin-react-xandeslint-plugin-react-dom. This requires setting up thelanguageOptions.parserOptionswith your project'stsconfigfiles.// 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, }, }, }, ]);Enable type-aware ESLint rules in Vite
masterFor production applications, it is recommended to enable type-aware lint rules by replacing
tseslint.configs.recommendedwith more specific configurations in your ESLint config. You must also configureparserOptionsto point to yourtsconfigfiles.Available
tseslintconfigurations:tseslint.configs.recommendedTypeCheckedtseslint.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, }, }, }, ]);Configure htmlparser2 options
masterYou can override default
htmlparser2options.Warning:
htmlparser2options 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, }, });Remove whitespace using the trim option
masterBy default, whitespace is preserved. To remove whitespace, enable the
trimoption.// Default behavior (whitespace preserved) parse('<br>\n'); // [React.createElement('br'), '\n'] // With trim enabled parse('<br>\n', { trim: true }); // React.createElement('br')Note: Enabling
trimmay strip out intentional whitespace, such as in<p> </p>.parse('<br>\n', { trim: true }); // React.createElement('br')Prevent tag name lowercasing
masterBy default, tags are lowercased during parsing. To preserve the case of tags (e.g., for
<CustomElement>), pass thelowerCaseTags: falseoption within thehtmlparser2configuration 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')Fix TypeScript error in htmlparser2
masterIf you see the following TypeScript error:
node_modules/htmlparser2/lib/index.d.ts:2:23 - error TS1005: ',' expected.Upgrade to the latest version of
typescriptto resolve this.Fix TypeScript 'attribs' property error
masterIf you receive the TypeScript errorProperty 'attribs' does not exist on type 'DOMNode', it is because the node needs to be identified as an instance ofElementfromdomhandler. You may need to use type assertion or check the instance type.