Home > Enterprise >  Material ui 'sx' property does not take the new value of my themeProvider
Material ui 'sx' property does not take the new value of my themeProvider

Time:05-01

in my code i added custom createTheme and when i tried to change the box background it takes the default value which is blue idk what I'm doing wrong here

import React from 'react'
import { Typography , Button } from '@material-ui/core';
import BatteryAlertIcon from '@mui/icons-material/BatteryAlert';
import { purple, red } from '@material-ui/core/colors';
import { createTheme  , ThemeProvider } from '@material-ui/core'
import { Drawer } from '@mui/material';
import { Alert } from '@mui/material';
import Container from '@mui/material/Container';
import Box from '@mui/material/Box';

const theme = createTheme({
    palette: {
        primary:{
          main:purple[500]
        },
        secondary:{
          main:red[700]
        }
    },
    
})

function Start() {
    
  return (
    <ThemeProvider theme={theme}>
        <Container fixed >
          <Alert severity="error">This is an error alert — check it out!</Alert>
          <Box sx={{
            bgcolor:'primary.main', <<<------- shows blue color (default value)
            width:'100%',
            display:'flex',
            pt:'20rem'
          }}>
            <Button variant="contained" disableElevation component='h2'>CLICK ME</Button>
          </Box>

        </Container>

    </ThemeProvider>
  )
}

export default Start

I tried search for the solution but there's no clear answer

CodePudding user response:

It's happening because you're passing the property value as string. Do this instead

import React from 'react'
import { Typography , Button } from '@material-ui/core';
import BatteryAlertIcon from '@mui/icons-material/BatteryAlert';
import { purple, red } from '@material-ui/core/colors';
import { createTheme  , ThemeProvider } from '@material-ui/core'
import { Drawer } from '@mui/material';
import { Alert } from '@mui/material';
import Container from '@mui/material/Container';
import Box from '@mui/material/Box';

const theme = createTheme({
    palette: {
        primary:{
          main:purple[500]
        },
        secondary:{
          main:red[700]
        }
    },
    
})

function Start() {
    console.log(theme,"THEME")
  return (
    <ThemeProvider theme={theme}>
        <Container fixed >
          <Alert severity="error">This is an error alert — check it out!</Alert>
          <Box sx={{
            bgcolor: theme.palette.primary.main, //<<<------- now shows purple color (default value)
            width:'100%',
            display:'flex',
            pt:'20rem'
          }}>
            <Button variant="contained" disableElevation component='h2'>CLICK ME</Button>
          </Box>
        </Container>
    </ThemeProvider>
  )
}

export default Start

Output: enter image description here

  • Related