'Adding New Component Props Inside CreateTheme V5
How can I add new props to a component inside createTheme in version 5? I see how to add new variants but not new props. Also is there a way to know what TypeScript interfaces there are to extend / augment for this purpose?
Below seems like an example of how to add a variant, however I want "hoverable" to be a prop.
Example:
MuiCard: {
variants: [
{
props: { variant: "hoverable" },
style: {
"&:hover": {
boxShadow: "0px 12px 30px rgba(37, 15, 127, 0.08)",
},
},
},
],
}
TypeScript ( This doesnt seem right / work ):
declare module "@material-ui/core/Card" {
interface CardPropsVariantsOverrides {
hoverable: true;
}
}
Solution 1:[1]
This is how I'd do it (taken from mui.com)
import * as React from 'react';
import { styled, createTheme, ThemeProvider } from '@mui/system';
interface MyThemeComponentProps {
color?: 'primary' | 'secondary';
variant?: 'normal' | 'dashed';
}
const customTheme = createTheme({
components: {
MyThemeComponent: {
styleOverrides: {
root: {
color: 'darkslategray',
},
primary: {
color: 'darkblue',
},
secondary: {
color: 'darkred',
backgroundColor: 'pink',
},
},
variants: [
{
props: { variant: 'dashed', color: 'primary' },
style: {
border: '1px dashed darkblue',
},
},
{
props: { variant: 'dashed', color: 'secondary' },
style: {
border: '1px dashed darkred',
},
},
],
},
},
});
const MyThemeComponent = styled('div', {
// Configure which props should be forwarded on DOM
shouldForwardProp: (prop) => prop !== 'color' && prop !== 'variant',
name: 'MyThemeComponent',
slot: 'Root',
// We are specifying here how the styleOverrides are being applied based on props
overridesResolver: (props, styles) => [
styles.root,
props.color === 'primary' && styles.primary,
props.color === 'secondary' && styles.secondary,
],
})<MyThemeComponentProps>(({ theme }) => ({
backgroundColor: 'aliceblue',
padding: theme.spacing(1),
}));
export default function UsingOptions() {
return (
<ThemeProvider theme={customTheme}>
<MyThemeComponent sx={{ m: 1 }} color="primary" variant="dashed">
Primary
</MyThemeComponent>
<MyThemeComponent sx={{ m: 1 }} color="secondary">
Secondary
</MyThemeComponent>
</ThemeProvider>
);
}
Solution 2:[2]
The error you're getting, should be something like this -
The types of 'props.variant' are incompatible between these types.
Type 'string' is not assignable to type '"dashed" | "outlined" | "text" | "contained" | undefined'.
It says, variant
can only accept '"hoverable" | "outlined" | "text" | "contained" | undefined'
Try using props: { variant: "hoverable" as const }
instead of props: { variant: "hoverable" }
.
For more detail on this typescript issue check - Typescript Type 'string' is not assignable to type
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Suraj Rao |
Solution 2 | Rishav Pandey |