How to create one Custom MUI Color palette for whole App?

Viewed 1053

I want to create one color palette and use it in the whole project. So, I've created one in my App.js file. Here's the code:

import { Navigate, Route, Routes } from 'react-router-dom';
import Home from './Components/Home';
import Dashboard from './Pages/Dashboard';
import SignIn from './Pages/SignIn';
import SignUp from './Pages/SignUp';
import { createTheme, ThemeProvider } from '@mui/material/styles';

const theme = createTheme({
  palette: {
    black: {
      main: '#0D0D0D',
    },
    white: {
      primary: '#F2F2F2',
    },
    cream: {
      main: '#736555',
    },
    green: {
      main: '#5FD98A',
    },
    greenDark: {
      main: '#5EBF80',
    },
  },
});

function App() {
  return (
    <ThemeProvider theme={theme}>
      <Routes>
        <Route path='/' exact element={<Navigate to='dashboard' />} />
        <Route path='dashboard' element={<Dashboard />}>
          <Route index element={<Home />} />
        </Route>
        <Route path='login' element={<SignIn />} />
        <Route path='register' element={<SignUp />} />
      </Routes>
    </ThemeProvider>
  );
}

export default App;

But, When I use it in the Cards Component,(which is inside of the Home component, the bgcolor is not working. Here's my Cards Component's code:

import Card from '@mui/material/Card';
import CardContent from '@mui/material/CardContent';
import Typography from '@mui/material/Typography';
import { Link } from 'react-router-dom';

function Cards(props) {
  return (
    <ThemeProvider theme={theme}>
      <Card sx={{ bgcolor: 'greenDark.main' }}>
        <Link to={'/'}>
          <CardContent>
            <Typography gutterBottom variant='h5' component='div'>
              Lizard
            </Typography>
            <Typography variant='body2' color='text.secondary'>
              Lizards are a widespread group of squamate reptiles, with over
              6,000 species, ranging across all continents except Antarctica
            </Typography>
          </CardContent>
        </Link>
      </Card>
    </ThemeProvider>
  );
}

export default Cards;

I want to create one color palette and use it no the whole project. Can anybody help me out here how can I do that?

Note: If I create the color palette in the Cards component again, then the color works. But this is not what I'm looking for. And I'm using the latest version of everything. React-Router, Material UI, React.

1 Answers

In MUI paper component's background is picked from palette.background.paper Which is missing hence, your paper component's background is not changing. Your theme setup is correct no issue from that side.

palette: {

      background: {
        default: "#f4f6f8",
        dark: '#f4f6f8',
        paper: "#fff"
      }
      
    }
Related