'How to have custom colors as props with mui v5 react typescript?
I wish to add one or more custom color props values to the MUI Button component. I followed https://javascript.plainenglish.io/extend-material-ui-theme-in-typescript-a462e207131f, which almost worked. I used the custom properties I created in the createPalette.d.ts file, but when I try to use that in a custom component, it throws an error, and I cannot use the custom color.
Error faced:
I followed Can't customize color palette types on Material UI theme in TypeScript, Material UI 5.0 Typescript React Custom theme, How to extend Material-UI Theme with Typescript? but no luck.
But, it is working here for the JavaScript version: Can you add an additional color in Material UI?. But, I am unable to follow it for the typescript version
As there are multiple files, I created a sandbox for the same. https://codesandbox.io/s/async-rgb-9m6ulo?file=/src/App.tsx
How can I accomplish it?
Solution 1:[1]
Add appcolor as a possilbe type in your ButtonPropsType.ts
type ButtonPropsType = {
color?:
| "inherit"
| "primary"
| "secondary"
| "success"
| "error"
| "info"
| "warning"
| "appcolor"; //<-- Here
disabled?: boolean;
variant?: "text" | "outlined" | "contained";
};
Alternatively if you want to dynamically add options as needed, mui has an interface for that.
ButtonPropsTypes.ts
import { ButtonProps } from "@mui/material";
type ButtonPropsType = {
color?: ButtonProps["color"];
disabled?: boolean;
variant?: "text" | "outlined" | "contained";
};
export default ButtonPropsType;
createPalette.d.ts
import * as createPalette from "@mui/material/styles/createPalette";
declare module "@mui/material/styles/createPalette" {
interface PaletteOptions {
appcolor?: PaletteColorOptions;
}
interface Palette {
appcolor: PaletteColor;
}
}
declare module "@mui/material" {
interface ButtonPropsColorOverrides {
appcolor;
}
}
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 | Cody Duong |

