mui / material-ui

Material UI: Comprehensive React component library that implements Google's Material Design. Free forever.
https://mui.com/material-ui/
MIT License
94.09k stars 32.33k forks source link

[Tabs] validateDOMNesting warning when Typography component is a child of TabPanel #30903

Open yongtheskill opened 2 years ago

yongtheskill commented 2 years ago

Duplicates

Latest version

Current behavior 😯

The contents of a TabPanel component are wrapped in a typography component. When a Typography (or other) component is a child of a TabPanel, this causes a validateDOMNesting warning.

Expected behavior 🤔

The TabPanel should be able to contain other components, other than just plain text, without causing a validateDOMNesting warning.

Steps to reproduce 🕹

Steps:

  1. Create TabPanel
  2. Add a <div> or <p> element as a child of the TabPanel

Here is a codesandbox with the Tabs demo code, but with one of the TabPanels containing a Typography component. Codesandbox

Context 🔦

This issue happened when trying to create UI that contains a Typography component inside of a TabPanel.

Your environment 🌎

`npx @mui/envinfo` ``` npmPackages: @emotion/react: latest => 11.7.1 @emotion/styled: latest => 11.6.0 @mui/material: latest => 5.4.0 react: latest => 17.0.2 react-dom: latest => 17.0.2 ```
aymanxdev commented 1 year ago

I done some investigation around validateDOMNesting warning and how it's implemented (thank you for the detailed description, it was v helpful), I've found that the warning is not from Material-UI itself, but rather from the way the custom TabPanel component is structured in the provided codesandbox example.

In the TabPanel component definition, there is a Typography component that wraps the children prop:

<Box sx={{ p: 3 }}>
  <Typography>{children}</Typography>
</Box>

And when using the TabPanel component, a Typography component is passed as a child:

<TabPanel value={value} index={0}>
  <Typography>See console for error</Typography>
</TabPanel>

But I think you already knew that and this was intentional. So a straightforward solution would be to modify the custom TabPanel component to remove the wrapping Typography component:

<Box sx={{ p: 3 }}>
  {children}
</Box>

I have checked the repo code and Typography component is not designed to contain sub Typography components, and this adjustment aligns with that design principle.

If you must nest different Typography components, then another approach to this would be using one of the helpful variantMapping prop options they provide. So the change based on your code would be

<Box sx={{ p: 3 }}>
   <Typography  component="span">{children}</Typography>
</Box>

I hope this has helped you.

SiddharthaMishra-dev commented 5 months ago

Is there any turnaround for this warning from the browser?