material-uimakestyles

How can I use 'theme' made with 'createMuiTheme()' inside 'makeStyles()'?


I have made customTheme using createMuiTheme() and I used it in the <ThemeProvider>. Now, I want to make some custom styles using that customTheme inside the makeStyles() function. But makeStyles() is not getting my customTheme. It gets the default theme.

Code:

import React from 'react';

import { createMuiTheme, makeStyles, ThemeProvider } from '@material-ui/core';

const customTheme = createMuiTheme({
  palette: {
    primary: {
      main: '#f0f'
    },
  }
});

const useStyles = makeStyles((theme) => ({
  box: {
    height: '100px',
    width: '100px',
    backgroundColor: theme.palette.primary.main
  }
}));

export default function App() {

  const classes = useStyles();

  return (
    <ThemeProvider theme={customTheme}>

      <div className={classes.box}>
        makeStyles
      </div>

      <div style={{
        height: '100px',
        width: '100px',
        backgroundColor: customTheme.palette.primary.main
      }}>
        inline style
      </div>

    </ThemeProvider>
  );
}

Screenshot: Screenshot Image

As can see in the Screenshot, the first <div> has default deep blue color of Material-UI that is using makeStyles.

The second <div> has the custom color, that is using inline style.

So, how can I use the customTheme in makeStyles()?


Solution

  • Try ThemeProvider to wrap over App component, as per my understanding theme provided will be applied to react components wrapped under it. since "makeStyles div" is just an element styles didn't apply to it.

    Codesandbox Link - https://codesandbox.io/s/mui-custom-theme-f354x