Invariant Violation Error When Displaying HTML Text Using React

I am creating a React application that requires using an external API to get some text. The problem is that the text is returned as a string with HTML tags to show emphasis, for example:

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

I used dangerouslySetInnerHTML so

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

which worked most of the time, but I run instances in which the text returned by the API is formatted so that React throws the following error:

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

There seems to be no way to catch errors in the rendering function at the moment, so I can't just ignore the problematic ones and continue.

Is there a better way to handle things like text highlighting or highlighting with React, or is there perhaps a way to filter or catch lines that React might find problematic?

+5
source share
2 answers

This problem is really mysterious! I noticed that sometimes the chunks of text that I was trying to display contained < or > , which, it would seem, dropped React.

I replaced the regular expression with the tags that I wanted to save (replaced @@@ for the start tag with the class and *** for the closing tags), deleted all the < or > instances, and then replaced the placeholders with my original markup.

Removing these extra characters seems to fix the problem.

+4
source

I found that this problem occurs when html is passed in unsafe SetInnerHTML undefined or malformed, for example. trying to tweak () the html as if it were a string that makes it invalid.

 <div dangerouslySetInnerHTML={{ __html: content.substring(0, 360) }} /> 
+1
source

All Articles