A quick way to debug invalid dom nesting warning in React
Quickly find out where your Warning: validateDOMNesting(...): <p> cannot appear as a descendant of <p>. is coming from
How many times have you received an Invalid dom nesting error like the following one in React or Next.JS?
Warning: validateDOMNesting(...): <p> cannot appear as a descendant of <p>.
From the above error, it can be known that somewhere inside a <p> tag I have another <p> tag as its child and that's not allowed, so I'm getting the following error.
While the warning does provide a stack trace sometimes tracing down the element that is causing the error might give you a hard time. For example, let's look at the following error, while the error gives the element's trace where the error occurred, I wasn't able to find the error just from the stack trace because the project that I'm currently using was using `html-react-parser` library to parse HTML that was coming from the server.
The actual code that was giving me the error was:
<p className="render-html">{parse(htmlFromServer)}</p>
Now I didn't notice the above code as I was looking only for the following structure in my code.
<p>
<p>...</p>
</p>
But then something suddenly struck me, what if I use CSS to locate the element where the error is occurring, as I have the structure of the HTML given to me on the browser console.
So I copied the elements from stack trace and wrote the following line of CSS
And Tadaa, the culprit has been caught ๐๐จ
I finally noticed where the error was occurring and then noticed the above-given code snippet. And I then that the code rendering server html that contained a <p> tag, inside of a <p> tag so I changed that <p> tag to <div> and the problem is now fixed.