### Start the Next.js development server
Source: https://github.com/remarkablemark/html-react-parser/blob/master/examples/nextjs/README.md
Use these commands to launch the local development environment.
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
--------------------------------
### Install with NPM
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
Use this command to install the library via npm.
```sh
npm install html-react-parser --save
```
--------------------------------
### Install with Yarn
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
Use this command to install the library via Yarn.
```sh
yarn add html-react-parser
```
--------------------------------
### Install with CDN
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
Include these script tags in your HTML to use the library via a CDN. Ensure React is loaded first.
```html
```
--------------------------------
### Configure ESLint with React-Specific Rules
Source: https://github.com/remarkablemark/html-react-parser/blob/master/examples/vite/README.md
Integrate `eslint-plugin-react-x` and `eslint-plugin-react-dom` for enhanced React and React DOM linting. This requires installing these plugins.
```javascript
// 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: [
// Other configs...
// 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,
},
// other options...
},
},
]);
```
--------------------------------
### Configure ESLint for Type-Checked Rules
Source: https://github.com/remarkablemark/html-react-parser/blob/master/examples/vite/README.md
Use this configuration to enable type-aware lint rules in your ESLint setup. Ensure `tsconfig.node.json` and `tsconfig.app.json` are correctly configured.
```javascript
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}']
extends: [
// Other configs...
// 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,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
]);
```
--------------------------------
### Preserving Whitespace by Default
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
By default, the parser preserves whitespace. This example shows a newline character being included in the output.
```ts
parse('
\n'); // [React.createElement('br'), '\n']
```
--------------------------------
### Remove Element by Replacing with Fragment
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
Excludes an HTML element from rendering by replacing it with an empty React Fragment (`<>`). This example targets an element with `id='remove'`.
```tsx
parse('
', {
replace: ({ attribs }) => attribs?.id === 'remove' && <>>,
});
```
--------------------------------
### Replace Element and its Children Recursively
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
Replaces an element and its children by recursively processing them using `domToReact`. This example transforms a `p` tag into an `h1` and a nested `span` into a styled `span`.
```tsx
import parse, { domToReact } from 'html-react-parser';
const html = "
keep me and make me pretty!
";
const options = {
replace({ attribs, children }) {
if (!attribs) {
return;
}
if (attribs.id === 'main') {
return {domToReact(children, options)}
;
}
if (attribs.class === 'prettify') {
return (
{domToReact(children, options)}
);
}
},
};
parse(html, options);
```
--------------------------------
### Stripping Invalid Whitespace in Tables
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
Certain elements like `` automatically strip out invalid whitespace. This example shows a newline within a table being removed.
```ts
parse(''); // React.createElement('table')
```
--------------------------------
### Run Performance Benchmark
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
Execute the npm run benchmark command to measure the performance of the html-to-react conversion.
```sh
npm run benchmark
```
--------------------------------
### Using Preact Library
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
Specify the UI library to use, such as Preact, by passing its module to the `library` option.
```ts
parse('
', {
library: require('preact'),
});
```
--------------------------------
### Check Project Size
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
Use npx size-limit to analyze the size of the project, which is useful for performance optimization.
```sh
npx size-limit
```
--------------------------------
### Using Custom UI Library
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
Provide a custom object with `cloneElement`, `createElement`, and `isValidElement` functions to the `library` option for a custom UI library.
```ts
parse('
', {
library: {
cloneElement: () => {
/* ... */
},
createElement: () => {
/* ... */
},
isValidElement: () => {
/* ... */
},
},
});
```
--------------------------------
### Load html-react-parser with RequireJS
Source: https://github.com/remarkablemark/html-react-parser/blob/master/examples/requirejs/index.html
Configures RequireJS paths for the parser and React dependencies, then renders a parsed HTML string to the DOM.
```javascript
requirejs.config({ paths: { 'html-react-parser': '../../dist/html-react-parser.min', react: 'https://unpkg.com/react@18/umd/react.development', 'react-dom': 'https://unpkg.com/react-dom@18/umd/react-dom.development' } }); requirejs(['html-react-parser', 'react-dom'], (HTMLReactParser, ReactDOM) => { const root = ReactDOM.createRoot(document.getElementById('root')); root.render( HTMLReactParser(` HTMLReactParser loaded with RequireJS
`) ); });
```
--------------------------------
### Render HTML string with HTMLReactParser
Source: https://github.com/remarkablemark/html-react-parser/blob/master/examples/script/index.html
Uses ReactDOM.createRoot to mount a parsed HTML string into the DOM. Ensure the target element with the ID 'root' exists in your HTML.
```javascript
ReactDOM.createRoot(document.getElementById('root')).render( HTMLReactParser( '' + 'HTMLReactParser loaded with script tag' + '<\/h2>' ) );
```
--------------------------------
### Use Index in Replace Callback
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
Demonstrates that the `index` argument is provided to the `replace` callback, noting that it restarts for child nodes.
```ts
parse('
', {
replace(domNode, index) {
console.assert(typeof index === 'number');
},
});
```
--------------------------------
### Configure Webpack for html-react-parser
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
If encountering 'export "default" ... was not found' warnings, update your Webpack configuration to include 'browser' and 'main' in `resolve.mainFields`.
```javascript
// webpack.config.js
module.exports = {
// ...
resolve: {
mainFields: ['browser', 'main', 'module'],
},
};
```
--------------------------------
### Import ES Module
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
Import the parse function when using ES modules.
```ts
import parse from 'html-react-parser';
```
--------------------------------
### Render HTML to React via HTMLReactParser
Source: https://github.com/remarkablemark/html-react-parser/blob/master/examples/script/repl.html
Uses a textarea input to trigger the parser and updates a code block with the stringified output. Includes a replacer function to handle circular references during JSON serialization.
```javascript
var code = document.querySelector('code'); var textarea = document.querySelector('textarea'); function renderOutput(event) { cache = []; code.innerText = JSON.stringify( window.HTMLReactParser(event.target.value), replacer, 2 ); } textarea.addEventListener('input', renderOutput); renderOutput({ target: textarea }); /** * @see {@link https://stackoverflow.com/questions/11616630/json-stringify-avoid-typeerror-converting-circular-structure-to-json} */ var cache; function replacer(key, value) { if (typeof value === 'object' && value !== null) { if (cache.indexOf(value) !== -1) { // duplicate reference found return '[Circular]'; } // store value in our collection cache.push(value); } return value; }
```
--------------------------------
### Using Trusted Types Policy
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
Integrate a Trusted Types policy in the browser to sanitize HTML content before it's assigned to `innerHTML`. The `createHTML` method of the policy is called.
```ts
parse('
Hello
', {
trustedTypePolicy: window.trustedTypes?.createPolicy('my-policy', {
createHTML(input) {
// apply sanitization logic here
return DOMPurify.sanitize(input);
},
}),
});
```
--------------------------------
### Parse HTML with Self-Closing Tags
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
Demonstrates how non-void elements with self-closing syntax can lead to incorrect nesting. Ensure valid HTML markup for proper element nesting.
```javascript
parse(''); // returns single element instead of array of elements
```
--------------------------------
### Inspect DOM Node in Replace Callback
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
Logs the detailed structure of a DOM node to the console within the `replace` callback for inspection purposes.
```ts
parse('
', {
replace(domNode) {
console.dir(domNode, { depth: null });
},
});
```
--------------------------------
### Enabling XML Mode with htmlparser2
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
Override htmlparser2 options to enable `xmlMode` for parsing XML-like HTML structures. This option only works server-side.
```ts
parse('', {
htmlparser2: {
xmlMode: true,
},
});
```
--------------------------------
### Enabling Whitespace Trimming
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
Enable the `trim` option to remove leading and trailing whitespace from parsed elements. Be aware that intentional whitespace might also be stripped.
```ts
parse('
\n', { trim: true }); // React.createElement('br')
```
```ts
parse('
', { trim: true }); // React.createElement('p')
```
--------------------------------
### Parse HTML to React Elements
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
Use the `parse` function to convert an HTML string into React elements. This is the primary function for using the library.
```typescript
import parse from 'html-react-parser';
parse('Hello, World!
'); // React.createElement('p', {}, 'Hello, World!')
```
--------------------------------
### Render Parsed Adjacent Elements
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
Demonstrates how to render multiple parsed adjacent HTML elements correctly within a parent React component, such as a ``.
```tsx
{parse("
- Item 1
- Item 2
")}
```
--------------------------------
### Replace Element with TypeScript Type Check
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
Demonstrates how to safely replace elements in TypeScript by checking if `domNode` is an instance of `Element` before accessing its properties.
```tsx
import { HTMLReactParserOptions, Element } from 'html-react-parser';
const options: HTMLReactParserOptions = {
replace(domNode) {
if (domNode instanceof Element && domNode.attribs) {
// ...
}
},
};
```
--------------------------------
### Parse HTML Element with Attributes
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
Converts an HTML element with various attributes (including custom and style) into a React element.
```ts
parse(
'
',
);
```
--------------------------------
### Require CommonJS Module
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
Import the parse function when using CommonJS modules.
```ts
const parse = require('html-react-parser').default;
```
--------------------------------
### Parse Single HTML Element
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
Converts a simple HTML string into a React element.
```ts
parse('single
');
```
--------------------------------
### Convert DOM Attributes to React Props
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
Utilizes `attributesToProps` to convert HTML attributes of a DOM node into React props, demonstrated here for a `main` element.
```tsx
import parse, { attributesToProps } from 'html-react-parser';
const html = "
";
const options = {
replace(domNode) {
if (domNode.attribs && domNode.name === 'main') {
const props = attributesToProps(domNode.attribs);
return ;
}
},
};
parse(html, options);
```
--------------------------------
### Parse Multiple HTML Elements
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
Converts multiple adjacent HTML elements into React elements. Ensure they are rendered within a parent element.
```ts
parse('- Item 1
- Item 2
');
```
--------------------------------
### Replace Element with TypeScript Type Assertion
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
Shows an alternative TypeScript approach for replacing elements using a type assertion to `Element`.
```tsx
import { HTMLReactParserOptions, Element } from 'html-react-parser';
const options: HTMLReactParserOptions = {
replace(domNode) {
if ((domNode as Element).attribs) {
// ...
}
},
};
```
--------------------------------
### Conditional Replacement of Elements (v1+)
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
For versions v1.0.0 and later, the 'replace' option can be used to conditionally return JSX elements, such as replacing elements with a specific class with an empty fragment.
```tsx
import { Element } from 'domhandler/lib/node';
parse('
', {
replace(domNode) {
if (domNode instanceof Element && domNode.attribs.class === 'remove') {
return <>>;
}
},
});
```
--------------------------------
### Replace Element with Custom React Element
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
Uses the `replace` option to substitute a specific HTML element based on its attributes with a custom React component.
```tsx
parse('text
', {
replace(domNode) {
if (domNode.attribs && domNode.attribs.id === 'replace') {
return replaced;
}
},
});
```
--------------------------------
### Transforming React Elements
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
Use the `transform` option to modify each parsed React element. The callback receives the React node, DOM node, and index.
```tsx
parse('
', {
transform(reactNode, domNode, index) {
// this will wrap every element in a div
return {reactNode}
;
},
});
```
--------------------------------
### Parse Nested HTML Elements
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
Converts a string containing nested HTML elements into a React structure.
```ts
parse('Lorem ipsum
');
```
--------------------------------
### Prevent Tag Case Change in React
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
Pass the htmlparser2 option `lowerCaseTags: false` to preserve the original casing of tags. Be aware of potential React rendering warnings if custom components do not follow PascalCase.
```javascript
const options = {
htmlparser2: {
lowerCaseTags: false,
},
};
parse('', options); // React.createElement('CustomElement')
```
--------------------------------
### Type Assertion for DOM Nodes in TypeScript (v5+)
Source: https://github.com/remarkablemark/html-react-parser/blob/master/README.md
If encountering type errors related to DOM nodes in TypeScript, use type assertion to convert ChildNode[] to DOMNode[] when calling domToReact.
```typescript
domToReact(domNode.children as DOMNode[], options);
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.