DEV Community

Lukman Isiaka
Lukman Isiaka

Posted on

How to parse HTML to React

Recently, I have been working on a project, one of the requirement was that I should implement a Rich Text Editor and render the text firstly in a preview card as truncated text as shown in the image below

text truncated preview

Secondly, The main view, is where users get to read the content in detail. This was not a problem in particular as React provides us with a built-in solution to render raw HTML. dangerouslySetInnerHTML.

Problem

React built-in solution to my problem dangerouslySetInnerHTML works same way like vanilla JavaScript innerHTML. this is a risky solution because:

  • This solution by default exposes you to Cross Site Scripting (XSS), to be safe you'd have to use it alongside another package dom-purify to sanitize your HTML input.

  • The text rendered by this solution cannot be truncated because the way dangerouslySetInnerHTML works is by passing it as an attribute to a JSX element



<div dangerouslySetInnerHTML={{
__html: //htmlInput
}}> </div>


Enter fullscreen mode Exit fullscreen mode

and one of my project requirement is to have a preview of the content.

Solution

After doing so many research, I bumped into a package called html-to-react it's available on NPM, actively maintained and about 577k weekly downloads perfect!

The best thing about this package is that it solves the two problems I listed above.

I can now do



import HtmlToReactParser from "html-to-react";
import ReactTruncate from "react-truncated-component";
// other imports
function Wiki({body}) {
// other functions
return (
   <div className="wiki-card"> 
     <ReactTruncate numberOfLines={3} lineHeight={23}. 
       ellipsis="..." >
            <p className="w-hero__desc">. 
             {HtmlToReactParser.Parser().parse(
              body)}
            </p>
     </ReactTruncate>
   </div>
)
}


Enter fullscreen mode Exit fullscreen mode

Using the package this way, you will be able to truncate you r text anyhow you want and also render your HTML content nice and clean.

Peace ✌🏽.

Top comments (0)