Creating Custom Variants With Material-ui
I am trying to create custom variants for the Button component in Material-UI. My first step is to create a component based off of the Button component with the styles that I want:
Solution 1:
In Material-UI v5, you can easily create a new variants for your components (See the list of supported components in this RFC) using createTheme()
which removes the need to create wrapper components. Below is the minimum example:
const theme = createTheme({
components: {
MuiButton: {
variants: [
{
props: { variant: 'dashed' },
style: {
textTransform: 'none',
border: `2px dashed grey${blue[500]}`,
},
},
],
},
},
});
exportdefaultfunctionDemo() {
return (
<ThemeProvidertheme={theme}><Buttonvariant="outlined">
Outline
</Button><Buttonvariant="dashed">
Dashed
</Button></ThemeProvider>
);
}
For typescript users, you also need to update the variant definition using module augmentation.
declare module'@mui/material/Button' {
interface ButtonPropsVariantOverrides {
dashed: true;
}
}
Live Demo
Solution 2:
Two options are possible, it dont work cause you destruct "variant" and don't forward it to your MuiButton.
You can do it this way in your Button.js
constButton = ({ variant, ...muiButtonProps }) => {
if (variant === "cta") {
return<CTA {...muiButtonProps} />;
}
return<MuiButtonvariant={variant} {...muiButtonProps} />;
};
or
constButton = (muiButtonProps) => {
if (muiButtonProps.variant === "cta") {
return<CTA {...muiButtonProps} />;
}
return<MuiButton {...muiButtonProps} />;
};
Take a look at the docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
// Stage 4(finished) proposal
({a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40});
console.log(a); // 10
console.log(b); // 20
console.log(rest); // {c: 30, d: 40}
Post a Comment for "Creating Custom Variants With Material-ui"