Material components have built-in styles and options but in many cases you still need to customize (could be behavioral or styling changes). Today, I will show you how to add a new variant to a Button. Currently, it comes with three variants (text, contained, and outlined):
We are going to add a “pill” style as an option to make the button fully round. It is very common to have round and square buttons used interchangeably within a web app. Take Airbnb as an example, the search button is round while the signup is square.
Since we need to combine the round shape with different variants (like contained or outlined), it makes more sense to add it as separate property. So let’s get right into it!
npx create-react-app react-material-button-variant npm install @material-ui/core
We will create a new
Button.js component and inherit all properties from Material Button using
withStyles allows us to access the Button’s CSS API. In our case, we need to modify the
root rule name.
Also, as shown below, each rule accepts a function where the component’s props can be passed as a parameter. Now, by checking whether or not the
pill prop is added, we can easily change the button’s radius.
borderRadiusvalue with a sharable and more complex function that computes and customizes styles on the fly!
Finally, we can import the new custom button and add the
pill prop with different variants:
You might be asking why not just modify Material Theme Provider or add a new CSS class directly to the component? Why creating extra work and add a wrapper? Well, if you are using it once and the button has barely any customization then sure, it’s simpler to add a CSS class and get it done with. But if you have a fully customized design system that continuously adapts and progresses to meet new business requirements, then you need to think like a library provider, not just a developer. Meaning, you need to create isolated and composable components that support your design system and provide consistency across all products.
You can access the full repository here. I hope you enjoyed learning from this article and if you have any questions, please leave a comment below.