Home > Software engineering >  @mui/system -- how to pass transient props to styled()
@mui/system -- how to pass transient props to styled()

Time:02-16

I'm using import { styled } from "@mui/system"; like so:

const Column = styled("div")<ColumnProps>`
  background: ${(props) => props.backgroundColor ?? "blue"};
`;

export default function App() {
  return (
    <div>
      <Column backgroundColor={"green"}>column</Column>
    </div>
  );

and it is producing the following error:

Warning: React does not recognize the `backgroundColor` prop on a DOM element.

how can I pass a prop like this without having it trigger such an error? styled-components has "transient-props' that can be invoked with $ but that does not work with @mui/system

CodePudding user response:

In Emotion, this is handled via shouldForwardProp.

Here's a modified version of your sandbox:

import { styled } from "@mui/system";

type ColumnProps = {
  backgroundColor?: string;
};

const Column = styled("div", {
  shouldForwardProp: (prop) => prop !== "backgroundColor"
})<ColumnProps>`
  background: ${(props) => props.backgroundColor ?? "blue"};
`;

export default function App() {
  return (
    <div>
      <Column backgroundColor={"green"}>column</Column>
    </div>
  );
}

Edit React Typescript (forked)

MUI documentation: https://mui.com/system/styled/#heading-styled-component-options-styles-component

  • Related