Accessing previous theme variables in createMuiTheme
Asked Answered
I

2

25

Running Material UI 1.0.0-beta.24

I'm setting a new theme using createMuiTheme:

import {createMuiTheme} from 'material-ui/styles';

const theme = createMuiTheme({
  typography: {
    fontSize: 16
  }
});

export default theme;

How can I access the theme I'm overriding directly here ? I'd like to do this, which is not working :

import {createMuiTheme} from 'material-ui/styles';

const theme = createMuiTheme({
  typography: {
    fontSize: theme.typography.fontSize + 2
  }
});

export default theme;
Incisive answered 26/12, 2017 at 11:1 Comment(0)
C
64

You'd need to create an instance of the default theme and use it when defining your own:

import { createMuiTheme } from 'material-ui/styles';

const defaultTheme = createMuiTheme();

const theme = createMuiTheme({
  typography: {
    fontSize: defaultTheme.typography.fontSize + 2
  }
});

export default theme;
Cunnilingus answered 28/12, 2017 at 13:29 Comment(5)
is there any perfomance related issues with doing this at all?Primalia
This worked but I ended up with a lot of duplicate styles (not just overrides, but the exact same declaration). Maybe this would have cleared up in a build (I only tried during development), but the below answer from @zeckdude worked fine for me.Canella
You could also use the new experimental sx syntax. Although I can't figure out how to use itFleta
@Fleta You would still need access to the theme object to do this. The sx prop for components supports a callback that accepts theme as its parameter, but this isn't the case with the experimental syntax for defining themes.Cunnilingus
Anyone know how you might do this in v5 AND access component styles? Use case; I want to derive a margin based on the default theme InputBase margin and a style override I've applied elsewhere.Merola
G
8

You can also create your theme and then add on to it after theme is created.

import { createMuiTheme } from 'material-ui/styles';

const theme = createMuiTheme();
theme.typography = {
  ...theme.typography,
  fontSize: theme.typography.fontSize + 2
}

export default theme;
Gastroenterostomy answered 20/7, 2019 at 17:25 Comment(2)
This one will not work in different situations. For example, If you are passing the theme down to other components as the main theme using <themeProvider> then the default properties won't exist anymore. The example you used where you overwritten typography, some of the properties by default that were attached to typography aren't there anymore causing errors for components that rely on those variables. If you want to use just one default theme the solution provided above by Ken is more suitable.Celerity
You’re right. I have updated my answer to keep all the default typography properties and only overwrite the fontSize property. Thanks for the heads up.Gastroenterostomy

© 2022 - 2024 — McMap. All rights reserved.