react-parse-htmlstring

4.0.1 • Public • Published

ReactParseHTMLString

Parse any string and return a React component on a html container of your choice!

THE STORY BEHIND THIS LIBRARY!

Once upon a time...

Nah, Just kidding!  It's about a recent work of mine that requires some crazy html string and the likes to be rendered as html!  It could be a combination of or one of the following:

  • Given that <strong>max</strong>, <strong>x</strong> and <strong>y</strong> are declared and initialized, write a solution that if x<y returns <strong>max=x</strong>!
  • if (x<y)
        max=x;
    else
        max=y;
  • a[1] = 6;
    List<Integer> lst = new ArrayList<>();

The issue starts with the browser automatically treating any character or word after "<" as a html tag!  And of course, any non-valid html tag like <y or <Integer> from above examples will only be omitted!

Secondly, we also can not "html encode" these strings or even replace with its corresponding html entity since that would lead to literally rendering a valid html tag instead of the intended output such as the <strong>max</strong> where max is intended to be rendered bold!

And so, if you're still here... introducing react-parse-htmlstring!

Try the Live Demo!

Install

npm install react-parse-htmlstring
# or
yarn add react-parse-htmlstring

Usage

import React from 'react';
import ParseHTML, { parseHTMLString } from 'react-parse-htmlstring';

function HtmlComponent() {
	const htmlString = 'Even with x<y <i>I am still <strong>Strong!</strong></i>';
	return <ParseHTML
		string={ htmlString }
		className="demo"
		style={ { padding: '0.5rem', borderRadius: '1px solid gainsboro' } }
	/>;
}

API

component <ParseHTML />

Takes a few props and returns equivalent React element

Usage

import ParseHTML from 'react-parse-htmlstring';

props

  • string: Any string you need parsing!
  • className: CSS classname/s you can attach to style the component
  • style: If you prefer inline styling to above className... or use them both!
    • { borderRadius: '1px solid gainsboro' }: For example.
  • wrapperElement: Any html container element.
    • div: As default when none is provided.

function parseHTMLString

Takes any string and returns a parsed and safe HTML string if you're just like me that has some situations where the dangerouslySetInnerHTML has to be used .

Usage

import { parseHTMLString } from 'react-parse-htmlstring';

argument

  • string: Any string you need parsing!
NOTE:

For any undesired rendering/result, please do file an issue right here!.

Surely, I will immediately jump on it as soon as I can.  Cheers!

--sim

Powered by: sImo

Package Sidebar

Install

npm i react-parse-htmlstring

Weekly Downloads

70

Version

4.0.1

License

ISC

Unpacked Size

26.8 kB

Total Files

7

Last publish

Collaborators

  • jaosimt