In this blog post, I will explain how I successfully resolved the error message “dangerouslySetInnerHTML
did not match” in a React application. This solution applies not only to Next.js projects but also to any React code.
When attempting to print the HTML content of a prop using the dangerouslySetInnerHTML
attribute, I encountered the following error in the browser console:
Warning: Prop `dangerouslySetInnerHTML` did not match.
Initially, I found it perplexing because the HTML string would momentarily appear and then disappear. However, I discovered that the issue was due to nesting <p>
tags within another <p>
tag.
To illustrate, consider the following code snippet:
<p dangerouslySetInnerHTML={{ __html: '<p>test</p>' }}></p>
Although the error message may seem cryptic at first, I realized that nesting <p>
tags inside each other was causing the problem. To fix this, I simply switched to using a <div>
element instead:
<div dangerouslySetInnerHTML={{ __html: '<p>test</p>' }}></div>
This modification resolved the issue, and the content was successfully rendered.
Conclusion
By avoiding the nesting of <p>
tags within one another, I was able to resolve the “dangerouslySetInnerHTML did not match” error in my React application. If you encounter a similar issue, keep in mind that using a different element, such as a <div>
, may be necessary.
Tags: React, Next.js, dangerouslySetInnerHTML, HTML rendering