Home > Mobile >  React add custom property to component
React add custom property to component

Time:09-03

I am trying to create a variation of an MUI component. This all works fine, until I run the build command, and then it fails. I have a few variations of this, but basically I just want a custom property or attribute that changes some element of the component.

// RoundBox.js
import { styled } from "@mui/material/styles";
import MuiBox from "@mui/material/Box";

export const RoundBox = styled(MuiBox)(({roundish }) => ({
  borderRadius: roundish ? 5 : 15
}));

Using that component in another file like this:

<RoundBox>
 ... rounded content ...
</RoundBox>

<RoundBox roundish>
 ... very rounded content ...
</RoundBox>

This renders correctly, when I am running it in developer mode, however, when I try to build it, I am getting errors like this:

Type error: Type 'true' is not assignable to type 'ResponsiveStyleValue<MinWidth<string | number> | MinWidth<string | number>[] | undefined> | ((theme: Theme) => ResponsiveStyleValue<MinWidth<...> | MinWidth<...>[] | undefined>)'.

CodePudding user response:

I'm writing this from memory, but you need to tell the compiler the type of the props you expect:

type RoundBoxProps = {
  roundish: boolean
}

export const RoundBox = styled<RoundBoxProps>(MuiBox)(({ roundish }) => ({
  borderRadius: roundish ? 5 : 15
}));

You could also simplify this by an inline type, if you expect just a few props:

export const RoundBox = styled<{ roundish: boolean }>(MuiBox)(({ roundish }) => ({
  borderRadius: roundish ? 5 : 15
}));

CodePudding user response:

You can do it like

const RoundBox = styled(MuiBox)(({roundish}: {roundish: boolean}) => ({
  borderRadius: roundish ? 5 : 15
}));

or

<MuiBox sx={{ borderRadius: 5 }} />
<MuiBox sx={{ borderRadius: 15 }} />
  • Related