@kpsoftec/react-html-parser
v1.0.0
Published
A secure and flexible HTML parser for React with XSS protection and customizable component mapping
Downloads
22
Maintainers
Readme
@kpsoftec/react-html-parser
A secure and flexible HTML parser for React applications with built-in XSS protection and customizable component mapping.
Features
- 🔒 XSS Protection - Blocks dangerous tags, attributes, and URLs
- 🎨 Flexible Component Mapping - Map HTML tags to custom React components
- ⚡ TypeScript Support - Full type safety
- 🚀 Zero Dependencies - Uses native browser APIs
Installation
npm install @kpsoftec/react-html-parserUsage
Basic Usage
// Named import (recommended)
import { HtmlParser } from '@kpsoftec/react-html-parser';
// Or default import
import HtmlParser from '@kpsoftec/react-html-parser';
const App = () => {
const htmlContent = '<div><h1>Hello World</h1><p>Safe HTML parsing</p></div>';
return <HtmlParser htmlContent={htmlContent} />;
};Custom Component Mapping
import { HtmlParser } from '@kpsoftec/react-html-parser';
import { Typography, Button } from '@mui/material';
const componentMap = {
h1: { component: Typography, props: { variant: 'h1', color: 'primary' } },
button: { component: Button, props: { variant: 'contained' } }
};
const App = () => {
return (
<HtmlParser
htmlContent="<h1>Title</h1><button>Click me</button>"
componentMap={componentMap}
/>
);
};Disable XSS Protection
<HtmlParser
htmlContent={htmlContent}
enableXSSProtection={false}
/>API
HtmlParser (Recommended)
Props
| Prop | Type | Default | Description |
|------|------|---------|-------------|
| htmlContent | string \| null \| undefined | - | HTML string to parse |
| componentMap | Record<string, ComponentMapping> | {} | Custom component mappings |
| enableXSSProtection | boolean | true | Enable/disable XSS protection |
| allowedTags | string[] | [] | Tags to allow even with XSS protection |
| allowedAttributes | string[] | [] | Attributes to allow even with XSS protection |
HtmlStringParser (Basic)
Basic HTML parser without XSS protection or component mapping.
import { HtmlStringParser } from '@kpsoftec/react-html-parser';
<HtmlStringParser htmlString="<div>Basic HTML</div>" />Props
| Prop | Type | Description |
|------|------|-------------|
| htmlString | string | HTML string to parse |
ComponentMapping
interface ComponentMapping {
component: any;
props?: Record<string, any>;
}License
MIT
