The `react-sanitizer-parser` package is a React component and utility library designed to safely render HTML content within React applications, mitigating XSS vulnerabilities. It acts as a convenient wrapper around two well-established libraries: `html-react-parser` for converting HTML strings into React elements and `DOMPurify` for robust HTML sanitization. As of version 0.1.4, it provides a `<ReactSanitizerParser>` component that takes a `dirty` HTML string as children, along with optional `htmlParserOptions` and `sanitizerConfig` props to fine-tune the behavior of its underlying dependencies. Additionally, it re-exports the `parse` function from `html-react-parser` and the `DOMPurify` object directly for more granular, imperative usage. Its primary differentiator is simplifying the integration of HTML parsing and sanitization into React, offering a streamlined API compared to configuring both libraries independently.
npm install react-sanitizer-parserVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates the primary usage of the `ReactSanitizerParser` component, including how to pass `sanitizerConfig` for custom DOMPurify rules. It also shows the direct use of the re-exported `parse` function from `html-react-parser` and the `DOMPurify` object for imperative HTML processing.
Pass a custom `sanitizerConfig` prop to `ReactSanitizerParser` or `DOMPurify.sanitize()` directly, specifying allowed tags, attributes, and other rules according to your application's security requirements.
Always test `react-sanitizer-parser` thoroughly after updating its peer or direct dependencies. Consult the changelogs of `html-react-parser` and `DOMPurify` for potential impacts on sanitization rules or parsing logic.
When using `import { parse } from 'react-sanitizer-parser';`, ensure that the HTML string passed to `parse()` has been pre-sanitized using `DOMPurify.sanitize()` (also re-exported) or another trusted sanitizer. Example: `parse(DOMPurify.sanitize(dirtyHtml))`.Ensure that the `children` prop of `<ReactSanitizerParser>` is always a valid HTML string. If you have dynamic content that might not be a string, convert it explicitly or handle empty states.
Ensure that the `children` prop passed to `<ReactSanitizerParser>` is always an HTML string. For example: `<ReactSanitizerParser>{String(myContent)}</ReactSanitizerParser>` if `myContent` might be a number or null.Use the correct named import for `DOMPurify`: `import { DOMPurify } from 'react-sanitizer-parser';`This is typically a warning from React itself, not an error with `react-sanitizer-parser` if `DOMPurify` is configured to disallow `javascript:` URLs (which it does by default). Review your `DOMPurify` configuration via `sanitizerConfig` to ensure strict removal of such URLs. Consider replacing `javascript:` URLs with event handlers or preventing their insertion at the source.