Natalka
Natalka

Reputation: 438

Why does passing custom props to a MUI styled element cause a DOM element warning to appear?

I'm working with mui v5 in React with Typescript. I'm attempting to style a div, but am getting the following error in the console:

"Warning: React does not recognize the openFilterDrawer prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase openfilterdrawer instead. If you accidentally passed it from a parent component, remove it from the DOM element."

What am I doing wrong?

Here's my code:

  type ChipsContainerProps = {
    openFilterDrawer: boolean
  }

 const ChipStyled = {
    Container: styled('div')<ChipsContainerProps>(
      ({ theme, openFilterDrawer }) => ({
          //leaving out irrelevant theme code
          ...(openFilterDrawer && {
            transition: theme.transitions.create('margin', {
              easing: theme.transitions.easing.easeOut,
              duration: theme.transitions.duration.enteringScreen,
            }),
            marginLeft: 0,
            paddingLeft: '0rem',
          }),
        },        
      }),
    ),
  }

Upvotes: 5

Views: 1837

Answers (2)

niltonxp
niltonxp

Reputation: 440

An example using MUI version 5+

export const PaperContainer = styled(Paper, {
  shouldForwardProp: prop => prop !== 'gridArea',
  name: 'PaperContainer',
})<{ gridArea: GridArea }>(({ theme, gridArea }) => ({
  gridArea,
  padding: theme.spacing(6),
  overflow: 'hidden',
}));

Upvotes: 0

Steve G
Steve G

Reputation: 13377

The issue is that MUI is forwarding the openFilterDrawer prop that you're passing to the underlying div, and since openFilterDrawer is not a valid prop for divs, React is throwing that warning.

To clear the warning, you should pass an object containing a shouldForwardProps function to filter the prop from the resulting div. For example:

const ChipStyled = {
  Container: styled("div", {
    shouldForwardProp: (prop) => prop !== "openFilterDrawer" // <-- Here
  })<ChipsContainerProps>(({ theme, openFilterDrawer }) => ({
    //leaving out irrelevant theme code
    ...(openFilterDrawer && {
      transition: theme.transitions.create("margin", {
        easing: theme.transitions.easing.easeOut,
        duration: theme.transitions.duration.enteringScreen
      }),
      marginLeft: 0,
      paddingLeft: "0rem"
    })
  }))
};

Upvotes: 5

Related Questions