Change custom theme Material-UI

Viewed 23944

I am using Material-UI for a React project. However, I'm not sure as to how to apply a theme globally.

Here I have tried for individual components

import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import CardCommon from '../../common/card/CardCommon';

import purple from '@material-ui/core/colors/purple';
import Button from '@material-ui/core/Button';

import { Link } from 'react-router-dom';
//const primary = red[500]; // #F44336
import { Paths } from '../../../Routes';

const theme = createMuiTheme({
    palette: {
        primary: { main: purple[500] }, // Purple and green play nicely together.
        secondary: { main: '#11cb5f' }, // This is just green.A700 as hex.
    },
});

So how can I change the primary and secondary colors globally?

3 Answers

You can structure your app like this. Wrap the child components inside a MuiThemeProvider and pass a createMuiTheme object to it as a theme property value.

Also typography: {useNextVariants: true } fixes the following error:

(Warning: Material-UI: you are using the deprecated typography variants that will be removed in the next major release.)

The official Material UI docs have more detailed information on this:

Edit the index.js file as follows


    import React from 'react';
    import ReactDOM from 'react-dom'; 
    import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';  
    import './index.css';
    import App from './App';

    const theme = createMuiTheme({
       palette: {
          primary: {
             light: '#fff',
             main: 'rgb(23, 105, 170)',
             dark: '#000'
          },
          secondary: {
            main: '#f44336',
          },
       },
       typography: { 
          useNextVariants: true
       }
    });

    ReactDOM.render(
       <MuiThemeProvider theme = { theme }>
          <App />
       </MuiThemeProvider>, 
       document.getElementById('root')
    );

Material UI Version 5 code:

import { ThemeProvider, createTheme } from '@mui/material/styles';

const themeOptions = {
  palette: {
    type: 'light',
    primary: {
      main: '#3f51b5',
    },
    secondary: {
      main: '#f50057',
    },
  },
};

const theme = createTheme(themeOptions);

<ThemeProvider theme={theme}>
    <App />
</ThemeProvider>
Related