Parsing raw html in reactnative the right way


Recently I was making an app for allowing users to read stories on their topics of interest even when they are offline.Now in some of this stories the text was sometimes in italics and bold to show highlight important points and even for names of characters in a conversation.Also there were paragraphs after each sections.Showing the text in simple Text container was out of question so next possible alternatives were either to store text as markdown or raw html and parsing them to show content in my stories card.I will discuss why I chose raw html over markdown in later section of this article.

We can parse html directly using a webview and passing prop as html in src option. But I wanted to use native components to display my markup since my content was to be nested with other views and webview was not able to render raw html with padding on both sides.Additionally I wanted control over the font size of all html elements.I came across the react-native-htmlview module which suited my purpose since it rendered html elements as native views and I could style individual html elements based on my preferences.

Lets get started with implementation first…

First you need to install react-native-htmlview:

Import the module and pass raw html as follows:

Here stories is a variable that contains your raw html source.You can then customize your html elements as follows:

Why raw html over markdown?

Now coming back to my decision I first stored data as markdown in my json files. Now each story was about 300-600 words long and I tried to render it using react native markdown modules like react-native-markdown and react-native-simple-markdown.However the rendering time was terrible and my app crashed unexpectedly so I gave up that option and switch to raw html.Also I used json files directly for offline storage instead of wrappers like AsyncStorage,redux-persist or client side dbs like realm.You can find my tutorial on reading data from json file directly in react native along with the reasons to do so here.

Bonus Tip:

If you like to convert articles from rich text to raw html in the backend/content management side you can use react-rte module if your cms is in reactjs. It is based on Facebook’s opensourced Draftjs framework for reactjs. Unfortunately it does not support img tags yet, so you can use react-quill if you need image support.

Kindly upvote the article if you liked it and share your view/recommendations in the comments section.You can find my other article on reactnative,reactjs and nodejs here

Image source:Pixabay

Share post-
About Saurabh Mhatre 70 Articles
Currently working in web and hybrid application development