<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Albert Kombol</title>
    <description>The latest articles on Forem by Albert Kombol (@kalush89).</description>
    <link>https://forem.com/kalush89</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F552451%2F2a446e8e-4633-445d-adcc-938b20b990e6.png</url>
      <title>Forem: Albert Kombol</title>
      <link>https://forem.com/kalush89</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/kalush89"/>
    <language>en</language>
    <item>
      <title>How to Parse HTML string in React</title>
      <dc:creator>Albert Kombol</dc:creator>
      <pubDate>Mon, 20 Feb 2023 22:02:04 +0000</pubDate>
      <link>https://forem.com/kalush89/how-to-parse-html-string-in-react-53fh</link>
      <guid>https://forem.com/kalush89/how-to-parse-html-string-in-react-53fh</guid>
      <description>&lt;h2&gt;
  
  
  HTML strings can be parsed into a react element or component in a number of ways. Some are as follows.
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1. Use "dangerouslySetInnerHTML".
&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;dangerouslySetInnerHTML&lt;/code&gt;attribute is React's response to the use of &lt;code&gt;innerHTML&lt;/code&gt; in the DOM.&lt;br&gt;
Parsing HTML string via this method is as easy as passing the attribute an object comprised of the HTML string as the value and &lt;code&gt;__html&lt;/code&gt; as key.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

const htmlString = '&amp;lt;p&amp;gt;This is a simple paragraph&amp;lt;/p&amp;gt;';
const theObj = {__html:htmlString};
const MyComponent = () =&amp;gt;{
    return &amp;lt;div dangerouslySetInnerHTML={theObj} /&amp;gt;
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;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, &lt;strong&gt;&lt;em&gt;dangerously&lt;/em&gt;&lt;/strong&gt; as a reminder.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. Use a library
&lt;/h3&gt;

&lt;p&gt;There are several libraries out there for parsing HTML string. Among these are &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://www.npmjs.com/package/react-html-parser" rel="noopener noreferrer"&gt;react-html-parser&lt;/a&gt;
According to this npm package's Readme, it converts standard HTML elements, attributes, and inline styles into their React equivalents&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;How to parse HTML string with react-html-parser&lt;/em&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

import ReactHtmlParser from 'react-html-parser';

const MyComponent = () =&amp;gt; {
    const htmlString = '&amp;lt;div&amp;gt;A simple HTML string&amp;lt;/div&amp;gt;';
    return &amp;lt;div&amp;gt;{ ReactHtmlParser(htmlString) }&amp;lt;/div&amp;gt;;
  }


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://www.npmjs.com/package/react-html-parser" rel="noopener noreferrer"&gt;html-to-react&lt;/a&gt;
Parses each DOM element and converts it to a React tree with one single parent.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;How it's implemented&lt;/em&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

import { Parser } from "html-to-react";

const MyComponent = () =&amp;gt; {
const htmlParser = new Parser();
  const htmlString = '&amp;lt;span&amp;gt;&amp;lt;strong&amp;gt;Another simple html string&amp;lt;strong&amp;gt;&amp;lt;/span&amp;gt;';
return(
    &amp;lt;div&amp;gt;
            {htmlParser.parse(htmlString)}
    &amp;lt;/div&amp;gt;
  );
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://www.npmjs.com/package/html-react-parser" rel="noopener noreferrer"&gt;html-react-parser&lt;/a&gt;
This Parser works both on the server and client side and converts an HTML string to one or more React elements.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Usage is as follows&lt;/em&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

import parse from 'html-react-parser';
const MyComponent = () =&amp;gt; {
 const htmlString = '&amp;lt;div&amp;gt;A simple HTML string&amp;lt;/div&amp;gt;';
return &amp;lt;div&amp;gt;{parse(htmlString)}&amp;lt;/div&amp;gt;
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Let's weigh their popularity&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbzmtjgeod21xbkekqwzz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbzmtjgeod21xbkekqwzz.png" alt="All three html parser libraries popularity weighed on npmtrends" width="800" height="461"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;courtesy &lt;a href="https://npmtrends.com/html-react-parser-vs-html-to-react-vs-react-html-parser" rel="noopener noreferrer"&gt;npmtrends&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  3. Using reacts escape hatches
&lt;/h3&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://beta.reactjs.org/reference/react-dom/findDOMNode" rel="noopener noreferrer"&gt;findDOMNode&lt;/a&gt; as stated in React's docs, is focused on locating the root DOM node for a React class component instance.&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

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

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

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

export default MyComponent;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;findDOMNode is depricated and as such will not be available in future versions of React.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://beta.reactjs.org/learn/manipulating-the-dom-with-refs" rel="noopener noreferrer"&gt;Refs&lt;/a&gt; are used to access and manipulate DOM nodes directly. Below is how it's used when we wish to parse a html string.
```
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;import { useRef, useEffect } from "react";&lt;br&gt;
 const App = () =&amp;gt; {&lt;br&gt;
  const myRef = useRef(null);&lt;br&gt;
 useEffect(() =&amp;gt; {&lt;br&gt;
     myRef.current.innerHTML = '&lt;span&gt;&lt;strong&gt;Another simple html string&lt;strong&gt;&lt;/strong&gt;&lt;/strong&gt;&lt;/span&gt;';&lt;br&gt;
 }, [myRef])&lt;/p&gt;

&lt;p&gt;return &lt;/p&gt;;&lt;br&gt;
}



&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
###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.
&lt;/code&gt;&lt;/pre&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>react</category>
      <category>beginners</category>
    </item>
  </channel>
</rss>
