How do I change the Material-UI AppBar background colour?

6.8k views Asked by At

I'm creating an app using Material-UI components, and have changed the colours in the theme as follows (in src/index.js):

const theme = createMuiTheme({
  palette: {
    pale: {
        main: '#FCF4D9',
        contrastText: '#383838'
    }
  }
})

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

Then, in one of my components I want to use this to make the app bar have a pale background. I'm trying to do this as follows (src/Header/index.js):

const Header = () => {

  const theme = useTheme()
  
  return (
    <AppBar position="fixed" className="appBar" color={`${theme.palette.pale}`}>
      ...
    </AppBar>
  )
}

This isn't working - the background just comes out as white. If I rename "pale" to "primary" and then use

color="primary"

that works fine, but I already have another colour called "primary" so I can't do it that way.

I suspect that I'm doing the template literal wrongly, but I'm not sure - I've tried various other combinations of brackets, $ sign etc, but this is the only one that compiles. Or is it that I can only use "primary" and "secondary" in there, and not a theme property? If so, how do I use the theme property?

1

There are 1 answers

2
Nathan Getachew On BEST ANSWER

I hope this helps, Material-UI lets you customize Your own theme.

import { createMuiTheme } from '@material-ui/core/styles';
import purple from '@material-ui/core/colors/purple';
import green from '@material-ui/core/colors/green';

const theme = createMuiTheme({
  palette: {
    primary: {
      main: purple[500],
    },
    secondary: {
      main: green[500],
    },
    pale: {
     main: '#FCF4D9',
     contrastText: '#383838',
    }
  },
});

UPDATED

Once you customize your theme, you can use the different colors on your components based on their names. For example, In your src/Header/index.js Component, You can do this:

const useTheme = makeStyles((theme) => ({
  header: {
    color: theme.pale.main,
  },
}));

const Header = () => {

    const theme = useTheme()

    return (
        <AppBar position="fixed" className="appBar" color={theme.header}>
        ...
        </AppBar>
    )
}