Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invariant Violation error when displaying HTML-formatted text with React

I'm building a React application that requires using an external API to get some text. The problem is that the text comes back as a string with HTML tags to show emphasis, for example:

{ "text": ["The quick <em class='hl'>brown</em> fox"] }

I had been using dangerouslySetInnerHTML like so

{this.props.text.map(function(snippet) {
   return <div dangerouslySetInnerHTML={{__html: snippet }}></div>
})}

which worked most of the time, but I'm running into instances in which the text returned by the API is formatted in such a way that React throws the following error:

Uncaught (in promise) Error: Invariant Violation: 
Danger: Expected markup to render 7 nodes, but rendered 4

It seems there is currently no way to catch errors in the render function, so I can't just ignore problematic ones and continue.

Is a better way to handle things like text emphasis or highlighting with React, or perhaps there is a way to filter or trap strings that React may find problematic?

like image 219
jczaplew Avatar asked Jul 09 '15 04:07

jczaplew


1 Answers

This problem really is cryptic! I noticed that occasionally the text snippets I was attempting to display contained < or >, which were seemingly throwing off React.

I did a regex replace on the tags I wished to keep (replaced them with @@@ for the starting tag with the class and *** for the closing tags), removed all instances of < or >, and then replaced the placeholders with their original markup.

Removing these extra symbols seems to have fixed the problem.

like image 180
jczaplew Avatar answered Sep 22 '22 23:09

jczaplew