AI Workshop: learn to build apps with AI →
Debugging: How to fix the dangerouslySetInnerHTML did not match error in React

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


I was trying to print the HTML contained in a prop, using dangerouslySetInnerHTML, while I got this error in the browser console:

Warning: Prop `dangerouslySetInnerHTML` did not match.

This was a Next.js project, but the solution applies to any React code.

The string I was trying to print appeared for a while, and then disappeared. Quite strange!

It was even stranger when I tried to print a fixed HTML string, like this:

<p
  dangerouslySetInnerHTML={{
    __html: '<p>test</p>'
  }}></p>

The error message is cryptic but after a while, I realized I could not set a p tag inside another p tag.

Switching to:

<div
  dangerouslySetInnerHTML={{
    __html: '<p>test</p>'
  }}></div>

worked like a charm.

Lessons in this unit:

0: Introduction
1: How to handle errors in React
2: Fix the “Objects are not valid as a React child” error
3: Fix Uncaught Error Objects are not valid as a React child
4: How to use useEffect callback with event callbacks
5: How to debug a React application
6: ▶︎ How to fix the dangerouslySetInnerHTML did not match error in React
7: React, how to fix the TypeError: resolver is not a function error
8: How to fix the "cannot update a component while rendering a different component" error in React
9: Testing React components
10: How to configure HTTPS in a React app on localhost