Material UI global css variables
Asked Answered
G

4

5

I would like to declare some css variables that I will reuse among my components. This is how you do it with plain css:

:root {
  --box-shadow: 0 2px 5px -1px rgba(0, 0, 0, 0.3);
}

That would then be used as follows:

.my-class {
  box-shadow: var(--box-shadow);
}

How can I achieve the same with useStyles? I tried the following with no avail:

const theme = createMuiTheme({
  shadowing: {
    boxShadow: "0 2px 5px -1px rgba(0, 0, 0, 0.3)",
  }
});

My main App is enclosed within

<ThemeProvider theme={theme}>
  <App />
</ThemeProvider>

I tried using it in my component:

const useStyles = makeStyles(theme => ({
  workImage: {
    boxShadow: theme.shadowing,
  },
}));

But it's not working.

Gardia answered 8/12, 2019 at 2:0 Comment(0)
D
2

"createMuiTheme" function accepts object with limited set of keys.(palette, Typography, spacing...etc)

You can use just normal object.

const theme = {
  shadowing: {
     boxShadow: "0 2px 5px -1px rgba(0, 0, 0, 0.3)",
  }
};
Dada answered 8/12, 2019 at 2:39 Comment(0)
G
9

In my case I had to use both createMuiTheme and custom variables. To achieve it I did as follows.

First I created a theme with createMuiTheme

const theme = createMuiTheme({
  typography: {
    fontFamily: "verdana",
  },
});

Then I created a separated object where I add my variables:

const cssVariables = {
  shadowing: {
     boxShadow: "0 2px 5px -1px rgba(0, 0, 0, 0.3)",
  }
};

Then I pass the two objects to my ThemeProvider:

<ThemeProvider theme={{ ...theme, ...cssVariables }}>

And finally, to access the variable:

const useStyles = makeStyles(theme => ({
  workImage: {
    boxShadow: theme.shadowing.boxShadow,
  },
}));
Gardia answered 8/12, 2019 at 2:50 Comment(0)
D
2

"createMuiTheme" function accepts object with limited set of keys.(palette, Typography, spacing...etc)

You can use just normal object.

const theme = {
  shadowing: {
     boxShadow: "0 2px 5px -1px rgba(0, 0, 0, 0.3)",
  }
};
Dada answered 8/12, 2019 at 2:39 Comment(0)
S
0

I achieved that by declaring a js const with the value and assigning it to the CSS property:

const color = "red";

    const useStyles = makeStyles((theme) =>
        createStyles({
            root: {
            color: color
            }
}));
Spunky answered 16/9, 2022 at 6:19 Comment(0)
A
0

Material UI (v5.6.0) now supports CSS variables as an experimental feature (docs).

Alysiaalyson answered 22/12, 2022 at 21:9 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.