How to override css properties of Material UI components

Viewed 3018

I am working on project in which I have to use Material UI, just for simplicity, consider I am having a simple functional component in which I am having 2 Material UI components Button and Text Field

import React from 'react';
import { Button, TextField } from '@material-ui/core';

function RenderComponent(){
    return(
        <>
            <Button variant="contained">Contained</Button>
            <TextField id="outlined-basic" label="Outlined" variant="outlined" />
        </>
    )
}

export default RenderComponent

Can anyone please tell me how to override the css properties of these 2 Material UI components.

Thankyou

2 Answers

Give them id's/classes and write your custom CSS for them. If it doesn't override the standard Material-UI styles, add the keyword !important. If you are using create-react-app, you can import CSS right to the file like this:

import "./styles.css";

If this doesn't help, that means Material-UI uses inline styles for the elements. In this case, you would have to write your CSS right into your components' attributes: like this. If it doesn't override standard styles, use !important again.

There are several ways to do this, you can directly override the built-in CSS class of an MUI component using the class name in your imported CSS file, for example in if you want to change the Button component's style, you can do this by applying your required CSS properties to .MuiButton-root class on your "CSS" file. Like bellow.

.MuiButton-root{
   color: white;
   height: 20px;
   padding: 10px;
}

You can also use the available props of a component, you can easily find them in their individual documentation page of mui site. Again you can use makeStyles or styled to style your component. Here is an example to use makeStyles in your Button component.

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import { Button, TextField } from '@material-ui/core';

const useStyles = makeStyles({

    root: {
          background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
          border: 0,
          borderRadius: 3,
          boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
          color: 'white',
          height: 48,
          padding: '0 30px',
        },
     });

function RenderComponent(){
    const classes = useStyles();
    return(
        <>
            <Button className={classes.root} variant="contained">Contained</Button>
            <TextField id="outlined-basic" label="Outlined" variant="outlined" />
        </>
    )
}

export default RenderComponent

You can find more about styles here.

Related