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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With