TamarG
TamarG

Reputation: 3570

Material UI Customized styled element with theme

I'm starting to use Material UI in my project. I have created a theme with some basic definitions, using my css variables:

import { createTheme } from '@mui/material/styles';
import theme from './_my-variables.scss';

const muiTheme = createTheme({
    palette: {
        primary: {
            main: theme['color-blue'], // 'color-blue' is my css variable
        },
    },
    typography: {
        fontFamily: theme['brand-font'], // 'brand-font' is my css variable
    },
}

I also used ThemeProvider in my App layout:

export const App = (props) => {
       return (<Provider store={store}>
             <ThemeProvider theme={muiTheme}>
                <ConnectedRouter history={historyRef.history}>
                   <Layout {...props} />
                </ConnectedRouter>
             </ThemeProvider>
      </Provider>);
};

I have a page with MUI elements, and it works fine and takes the new primary color and the new font.

<Box>
  <Paper>
    <Checkbox color="primary" />  <!-- I can see my new color in the page! Yay! -->
    some text
  </Paper>
</Box>

Now I want to create a custom element - like <MyCustomizeBox> that will have a different properties, using my css variables (for example - a specific width, defined in my variables).

How do I define them in my theme and how to use it to customize a new element? I prefer not to user classes () because I want to create a generic elements for reusing. Also I don't want to change all Boxes in my app - only the customized ones.

I tries to use "withStyles" but I was getting the default theme instead of my customized theme and I saw on Google that I'm not support to use both "withStyles" and theme together.

Upvotes: 0

Views: 236

Answers (1)

TamarG
TamarG

Reputation: 3570

At last, found the answer:

import { styled } from '@mui/system';

const MyCustomizedPaper = styled(Paper)(({ theme }) => ({
    width: theme.custom.myCustomWidthCssVar
}));

<MyCustomizedPaper ></MyCustomizedPaper >

Upvotes: 0

Related Questions