Fixing "<div> cannot appear as a descendant of <p>" Warning in React

Introduction

React, which is a popular JavaScript library for creating UI, is actually one of the better projects in terms of its helpful warnings. One of these warnings that developers often encounter is <div> cannot appear as a descendant of <p>.

In this Byte we'll show how to resolve this issue.

So what's the issue?

The <div> cannot appear as a descendant of <p> warning in React is actually caused by a violation of the HTML5 spec. According to the spec, the <p> tag can only contain "phrasing content", which includes text and inline elements like <span>. However, a <div> is a block-level element, and placing a block-level element inside a paragraph is not allowed by the spec.

<p>
  This is a paragraph with a <div>div inside it</div>.
</p>

In the above code, the <div> inside the <p> tag is causing the issue.

Identify the Problematic Element

To fix the warning, you first need to find the problematic element. This can typically be done by checking the console in your browser's developer tools. React warnings usually provide a stack trace that can help you locate the source of the issue.

Warning: validateDOMNesting(...): <div> cannot appear as a descendant of <p>.
    in div (at App.js:5)
    in p (at App.js:4)
    in div (at App.js:3)
    in App (at src/index.js:7)
Get free courses, guided projects, and more

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

In this example, the stack trace shows that the issue is in the App component, specifically at line 5 in App.js.

Fixing the Warning

Once you've identified the problematic element, you can fix the warning by replacing the <div> with an inline element that is allowed inside a <p>, such as a <span>, or by restructuring your HTML so that the <div> is no longer a descendant of a <p>.

<p>
  This is a paragraph with a <span>span instead of a div</span> đź‘Ť.
</p>

Or:

<div>
  <p>This is a paragraph.</p>
  <div>This is a div that's no longer inside the paragraph!</div>
</div>

Both of these solutions will resolve the warning as we now comply with the HTML5 spec.

Conclusion

To summarize, the <div> can't appear as a descendant of <p> warning in React due to the HTML5 specification for the <p> element, which can only contain phrasing content. By understanding the HTML5 content model and adjusting your code accordingly, you can easily resolve this warning. While these warnings might just seem like nuisances - they're there to help you write better, cleaner, and more compliant code.

Last Updated: August 11th, 2023
Was this helpful?

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms