DEV Community

Cover image for How to Parse HTML string in React
Albert Kombol
Albert Kombol

Posted on

How to Parse HTML string in React

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

1. Use "dangerouslySetInnerHTML".

The dangerouslySetInnerHTMLattribute 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} />
}


Enter fullscreen mode Exit fullscreen mode

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 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>;
  }


Enter fullscreen mode Exit fullscreen mode
  • html-to-react 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>
  );
}


Enter fullscreen mode Exit fullscreen mode
  • 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>
}


Enter fullscreen mode Exit fullscreen mode

Let's weigh their popularity

All three html parser libraries popularity weighed on npmtrends
courtesy npmtrends

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 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;


Enter fullscreen mode Exit fullscreen mode

findDOMNode is depricated and as such will not be available in future versions of React.

  • 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 = 'Another simple html string';
}, [myRef])

return

;
}

###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.

Top comments (0)