How to Parse HTML string in React
Tags: webdev, javascript, react, beginners
Published: 2023-02-20 22:02:04

HTML strings can be parsed into a react element or component in a number of ways. Some are as follows.
---

### 1. Use "dangerouslySetInnerHTML".
The `dangerouslySetInnerHTML`attribute is React's response to the use of `innerHTML` in the DOM.
Parsing HTML string via this method is as easy as passing the attribute an object comprised of the HTML string as the value and `__html` as key.


```
const htmlString = '<p>This is a simple paragraph</p>';
const theObj = {__html:htmlString};
const MyComponent = () =>{
    return <div dangerouslySetInnerHTML={theObj} />
}
```
There is a serious drawback to using this method, and this has to do with the fact that it exposes the app users to a  cross-site scripting (XSS) attack, hence, **_dangerously_** as a reminder.


### 2. Use a library
There are several libraries out there for parsing HTML string. Among these are 
- [react-html-parser](https://www.npmjs.com/package/react-html-parser)
According to this npm package's Readme, it converts standard HTML elements, attributes, and inline styles into their React equivalents

_How to parse HTML string with react-html-parser_
```
import ReactHtmlParser from 'react-html-parser';

const MyComponent = () => {
    const htmlString = '<div>A simple HTML string</div>';
    return <div>{ ReactHtmlParser(htmlString) }</div>;
  }
```
- [html-to-react](https://www.npmjs.com/package/react-html-parser)
Parses each DOM element and converts it to a React tree with one single parent.

_How it's implemented_
```
import { Parser } from "html-to-react";

const MyComponent = () => {
const htmlParser = new Parser();
  const htmlString = '<span><strong>Another simple html string<strong></span>';
return(
	<div>
    		{htmlParser.parse(htmlString)}
	</div>
  );
}
```

- [html-react-parser](https://www.npmjs.com/package/html-react-parser)
This Parser works both on the server and client side and converts an HTML string to one or more React elements.

_Usage is as follows_
```
import parse from 'html-react-parser';
const MyComponent = () => {
 const htmlString = '<div>A simple HTML string</div>';
return <div>{parse(htmlString)}</div>
}
```

**Let's weigh their popularity**

![All three html parser libraries popularity weighed on npmtrends](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bzmtjgeod21xbkekqwzz.png)
_courtesy [npmtrends](https://npmtrends.com/html-react-parser-vs-html-to-react-vs-react-html-parser)_

### 3. Using reacts escape hatches
React provides escape hatches to let your application connect and interact with systems outside the library. Simply put, they enable your application to directly manipulate the DOM.

- [findDOMNode](https://beta.reactjs.org/reference/react-dom/findDOMNode) as stated in React's docs, is focused on locating the root DOM node for a React class component instance.

```
import React from "react";
import ReactDOM from "react-dom";

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.placeholder = "Hello";
  }

  componentDidMount() {
    let htmlString = '<span><strong>Another simple html string<strong></span>';
    ReactDOM.findDOMNode(this).innerHTML = htmlString;
  }
  render() {
    return (
      <div>
        {console.log(this.placeholder)}
      </div>
    );
  }
}

export default MyComponent;
```
findDOMNode is depricated and as such will not be available in future versions of React.

- [Refs](https://beta.reactjs.org/learn/manipulating-the-dom-with-refs) are used to access and manipulate DOM nodes directly. Below is how it's used when we wish to parse a html string.
```
import { useRef, useEffect } from "react";
 const App = () => {
  const myRef = useRef(null);
 useEffect(() => {
     myRef.current.innerHTML = '<span><strong>Another simple html string<strong></span>';
 }, [myRef])
 
 return <div ref={myRef}/>;
}
```

###Important
Parsing HTML strings in React via the listed methods can be risky owing to the vulnerabilities this will bring to the application. Yes, we are still talking about XSS. 

Direct DOM manipulations are discouraged, so try to avoid code that would use the `innerHTML` property of the DOM directly. 

Sanitizing the HTML string with libraries like DOMPurify, right before parsing with an HTML parser library is ideal as this ensures no harmful data is present after the parser caries out its primary task.