Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to render HTML emails in React app

I create an SPA React application that can send and receive email messages.

What is the best way to render received HTML email messages? The task becomes problematic when I receive a huge email message with a lot of images in base64 and HTML tags.

I receive the email as JSON HTML string from API and want to render it properly.

I tried two approaches:

  1. Render in div with dangerouslySetInnerHTML={{ __html: htmlMessageText }} - there is problem with safety
  2. Use my email editor in preview mode (Jodit) - there is problem with Layout Thrashing

In both approaches, there is the problem with performance. Emails (800 lines) renders a lot of time (~2 minutes).

There is no problem with simple HTML emails, these renders fast, but with some of them - especially bigger emails - application like to freeze layout.

like image 739
crowmw Avatar asked Jan 28 '23 11:01

crowmw


2 Answers

The performance problems are caused by big data-URI images. The safety problems can be solved by a sanitizer library. So your algorithm might look like this:

  1. Replace data: URIs with blob:. For inspiration you can check out the relevant part in the code of TinyMCE.
  2. Now that after step 1 there is much less markup left, pass it through an HTML sanitizer. I would recommend DOMPurify.
  3. dangerouslySetInnerHTML
like image 99
thorn0 Avatar answered Jan 30 '23 00:01

thorn0


You could try a HTML to React parser... https://www.npmjs.com/package/react-html-parser.

like image 34
rooch84 Avatar answered Jan 30 '23 01:01

rooch84