An open API service indexing awesome lists of open source software.

https://github.com/thomasthiebaud/htmlstring-to-react

Convert a string containing html tags to an array of React elements. Light and secure
https://github.com/thomasthiebaud/htmlstring-to-react

html-parser react react-parser

Last synced: 9 months ago
JSON representation

Convert a string containing html tags to an array of React elements. Light and secure

Awesome Lists containing this project

README

          

# htmlstring-to-react

## Why ?

This module provide an easy way to parse a string containing html elements to an array of React elements. It tries to focus to security (using [DOMPurify](https://github.com/cure53/DOMPurify)) and keeping the bundle as small as possible

It is heavily inspired by [html2react](https://github.com/Deschtex/html2react) and [html-react-parser](https://github.com/remarkablemark/html-react-parser)

## How to install ?

npm install htmlstring-to-react
// or
yarn add htmlstring-to-react

## How to use ?

### Simple example

import { parse } from 'htmlstring-to-react'
parse('It\' is working')

### Add an override

You can use css selectors to override an element

import { parse } from 'htmlstring-to-react'
parse('It is working', {
overrides: {
b: (props, textContent) => {textContent}
},
})

All valid css selectors works

import { parse } from 'htmlstring-to-react'
parse('It is working', {
overrides: {
'b.active': (props, textContent) => {textContent}
},
})

**IMPORTANT** Overrides do not support nested elements in the current stage, so this code

import { parse } from 'htmlstring-to-react'
parse('It is working', {
overrides: {
b: (props, textContent) => {textContent}
},
})

will drop the inner `b` but keep the textContent

### Change dom parsing configuration

By default, we are sanitizing the html input using `DOMPurify` module. You can override the configuration we are using

import { parse } from 'htmlstring-to-react'
parse('It is working', {
dom: {
ADD_TAG: ['script']
},
})

**IMPORTANT** You cannot override `RETURN_DOM`, `RETURN_DOM_FRAGMENT` and `RETURN_DOM_IMPORT` because they are used internaly by the library.

### Other options

- **useFragment** (default `false`): Return a Fragment instead of an array.
- **useAsKey** (default `['key']`): Ordered list of attributes to use as a key. Use the first one that matches or `null`

## How to contribute ?

This repo enforce commit style so the release process is automatic. Commits must look like:

: Message starting with an uppercase

where SUBJECT is one of: `Fix`, `Update`, `New`, `Breaking`, `Docs`, `Build`, `Upgrade`, `Chore`

## Found a problem ?

Please open an issue or submit a PR, I will be more than happy to help