Mastering the art of customizing styles in Material UI v5 versus v4

When I first started using Material UI v4, I relied on makeStyles and withStyles from @mui/styles to customize the default styles of components in my application. It was a simple and effective approach to achieve the desired look and feel. However, with the transition to Material UI v5, I discovered that makeStyles has been deprecated and the styling system has undergone significant changes, now introducing the sx prop and styled API.

How can I now override default component styles, such as adjusting the padding or color of MuiButton, in Material UI v5? What are the recommended practices for globally or locally overriding default styles in MUI v5, and how does it differ from v4?

I would also appreciate examples demonstrating both global overrides using theming, as well as specific overrides through the sx prop or styled API.

Another query:

If I need to customize the style of a component based on its usage, or if I am creating a custom component using any of the Material UI components – like in this scenario:

import { Box } from "@mui/material";

function App() {
  return (
    <Box sx={{ bgcolor: (theme) => theme.palette.grey[100], p: 4 }}>
      <span>Hello world</span>
    </Box>
  );
}

export default App;

While I can easily utilize the sx prop to modify the style of the MUI component, I encounter limitations when trying to apply the same customization to the nested span element. How can I integrate colors from the theme without access to the sx prop for the nested elements?

Answer №1

Thank you for reading.

Here is an overview of the concept

  • Various color palettes are available

  • such as primary, secondary, etc.

  • To customize colors, use the palette property

    • Adjust the primary color as shown in the example
      • You can also modify secondary, success, error, info, warning colors
      • Add more properties by fixing typescript globally
  • To customize components throughout, utilize the components property

    • MuiButton
      • An example is provided for this component
    • MuiTable
    • MuiInput etc...
      • Consider default colors and design elements
      • Take care of their variants as well
import { createTheme, ThemeOptions, Theme } from '@mui/material/styles'

const primary = {
  main: '#7A5AF8',
  light: '#F4F3FF',
  dark: '#3E1C96',
  contrastText: '#FFFFFF',
  50: '#F4F3FF',
  100: '#EBE9FE',
  200: '#D9D6FE',
  300: '#BDB4FE',
  400: '#9B8AFB',
  500: '#7A5AF8',
  600: '#6938EF',
  700: '#5925DC',
  800: '#4A1FB8',
  900: '#3E1C96'
}

export const lightTheme: ThemeOptions = createTheme({
  palette: {
    primary,
  },
  components: {
    MuiButton: {
      defaultProps: {
        disableRipple: true,
        variant: 'contained'
      },
      styleOverrides: {
        root: {
          textTransform: 'none',
          borderRadius: '6px',
          padding: '10px 16px',
          fontWeight: 500
        }
      },
      variants: [
        {
          props: {
            variant: 'contained'
          },
          style: ({ theme }: { theme: Theme }) => ({
            paddingTop: theme.spacing(0.75),
            paddingBottom: theme.spacing(0.75),
          })
        }
      ]
    }
  }
})

  • Create a separate component to provide the theme
import CssBaseline from '@mui/material/CssBaseline'
import { ThemeProvider as MuiThemeProvider } from '@mui/material/styles'
import { lightTheme } from 'your-constant-location'


const ThemeProvider = ({ children }) => {
   return (
     <MuiThemeProvider theme={lightTheme}>
       <CssBaseline />
       <>{children}</>
     </MuiThemeProvider>
   )
}
 

Integrate this provider into your main app

const App = () => {
  return (
    <ThemeProvider>
       ...your app
    </ThemeProvider>

  )
}

Customize Locally

<Box
  sx={{
    bgcolor: (theme) => theme.palette.grey[100],
    p: 4,
    '& span': {
      color: 'blue',
      fontWeight: 'bold',
      fontSize: '20px',
    },
  }}
>
  <span>Hello world</span>
</Box>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The images are positioned within the middle of the page, directly beneath the sidebar, rather than at the top. (Vue.Js)

I'm currently working on a Vue.JS photo website and I've hit a roadblock as described in the title. Despite trying various solutions, after spending two hours back and forth with ChatGPT, I've decided to seek help here. Below is the code sn ...

Delete the line height (or leading) for bigger text in CSS

Is there a way to eliminate the space above and below the mandatory span, specifically when using << within it? The height of the field row is determined by the default line-height for the text size, but the mandatory field is taller due to its larg ...

Tips for creating a functional Submit button in HTML

How can I ensure that the submit button sends the necessary information to my email address when clicked (e.g. [email protected])? If PHP is required, please provide the code so I can easily integrate it into my project. Thank you! <div id="forms ...

Using the linearGradient feature within an SVG to create a transitional effect on the Fill property

Looking to implement a stepper functionality, everything is working smoothly except for the transition on the fill. let step = 0; document.querySelector("button").addEventListener('click', () => { step++; document.querySelector("svg ...

Delivering information to personalized components using React Bootstrap

I am working with a custom styled checkbox that is part of a mapped data array. {nfcArray && nfcArray.map((item, key) => { return ( <tr class="hover"> <td className="cell_style pl-3 pl-lg-5"> ...

What is the best way to replace an existing element in a useState object array in React Js instead of simply adding a

My useState object looks something like this: const [data, setData] = useState({ dish: "", category: "", cost: 0, qnty: 0, img: "", }) The qnty variable in the object is a counter. Whenever this counter is updated, ...

The Android material design concept does not incorporate rounded corners in the cardview feature on mobile devices

I am facing an issue with Cardview in Android X. <androidx.cardview.widget.CardView android:id="@+id/card_box_register" android:layout_width="match_parent" android:layout_height=" ...

Redux does not cause the components to re-render

One of my components is designed to extract data from the mapStateToProps() method. Here is the code for this component: handleClick = () => { if (this.props.data.status) { this.props.changeIpStatus(index, !this.props.data.statu ...

Is there a way to pass locale data using props in VueJS Router?

To access hotel data, the URL path should be localhost:8080/hotel/:id (where id is equal to json.hoteID). For example, localhost:8080/hotel/101 This path should display the specific data for that hotel. In order to achieve this, we will utilize VueJS vu ...

Tips for preventing a background image from repeating on a webpage

Check out this code snippet: div#bg { background-size: contain; background-repeat: no-repeat; } <div id="bg" v-bind:style="{ background: 'url(' + require('../assets/kafa.jpg') + ')' }"> I am trying to hav ...

Enhancing the appearance of standard HTML checkboxes

This HTML snippet displays a pair of checkboxes positioned side by side <div id="mr_mrs"> <ul class="mr_mrs form-no-clear"> <li id="mr" class="popular-category"> <label for="Mr" id="mr">Mr</label> ...

Is it possible to conceal or disregard text elements from the web browser search function by using CTRL+F?

I have a complex web application interface with a dedicated area for content display. Is there a way to ensure that when users utilize the browser's text search function (CTRL+F), the UI elements are ignored and only the actual content is searched? ...

Placing a new item following each occurrence of 'X' in React components

Currently, I am working with a React component that uses Bootstrap's col col-md-4 styles to render a list of items in three columns. However, I am facing an issue where I need to add a clearfix div after every third element to ensure proper display of ...

When I try to load a new model by clicking a link, the model briefly appears and then vanishes. This seems to be a problem with the material

Hello, I appreciate your help in advance. The project I've been working on is based on the code found at https://codesandbox.io/s/r3f-wouter-routes-7kohn I have expanded upon the above project by incorporating it into a larger project structure usin ...

How can we use the nth-of-type selector to target a set of eight elements in a

I am trying to style a group of divs in such a way that every set of eight elements will have the same left positioning. Rather than just styling every eighth element individually, I want to apply the styling to groups of eight elements at once. However, ...

Navigating with React Router updates the URL but doesn't cause the component to render

I am encountering an issue with a React Material-UI component where I want to render another React component by changing the URL. The Create Jobs component is located in another file. Despite exploring various solutions on Stack Overflow, none of them hav ...

The error message "Property '...' is not found on the type 'ServerContextJSONValue'" pops up whenever I try to utilize the useContext() function

After creating a Provider and defining the type, I encountered a TypeScript error when using it with useContext(): "Property '...' does not exist on type 'ServerContextJSONValue'. I'm not sure what I am missing. Can anyone help me ...

Is there a way to showcase the chosen value in a distinct manner compared to the options listed in the dropdown menu?

I am currently learning how to use materialUI and I want the dropdown menu to display the full region name while showing a shortened value when an option is selected (for example, 'NA1'). Is there a way to achieve this functionality? https://i.s ...

How can I ensure that a list of cards is 100% in height?

Can anyone assist me in setting the height of my grid cards? I am struggling to adjust the height of my grid card list, despite setting the parent element's height as well <div class="desc-grid__body cards-grid"> <ul clas ...