Freez
Freez

Reputation: 7568

material-ui : Extract color from theme

I want to use a color from my material-ui theme inside a component like that :

const MyComponent = props => (
   <UsersIcon color={currentTheme.primary1Color} />
)

So, my need is to extract a value from the current provided theme.

I found a working solution to solve this case, using context to retrieve the current theme :

const MyComponent = (props, {muiTheme}) => (
    <UsersIcon color={muiTheme.palette.primary1Color} />
)
contextTypes = {
    muiTheme: PropTypes.object.isRequired,
}

The React context is used "under the hood" by material-ui, so my solution is not future proof – the implementation of MUI can change –, is there any way to solve this in a proper (or recommended) way ?

Upvotes: 5

Views: 7191

Answers (3)

Spatz
Spatz

Reputation: 20118

You can access the theme variables with react hook or with higher-order component.

Example with hook:

//...
import { useTheme } from '@material-ui/core/styles';

const MyComponent = () => {
    const theme = useTheme();
    return <UsersIcon color={theme.palette.primary.main} />
}

Example with HOC:

//...
import { withTheme } from '@material-ui/core/styles';

const MyComponent = ({theme, ...other}) => {
    return <UsersIcon color={theme.palette.primary.main} />
}

export default withTheme(MyComponent)

Don't forget to wrap root application component with ThemeProvider

Another method to mention is makeStyles for CSS-in-JS styling:

//...
import { makeStyles } from '@material-ui/core/styles'
const useStyles = makeStyles(theme => ({
  icon: {
    color: theme.palette.primary.main
  }
}))

const MyComponent = () => {
  const classes = useStyles()
  return <UsersIcon className={classes.icon} />
}

Upvotes: 10

ykorach
ykorach

Reputation: 618

Yes you have! using muiThemeable..

import muiThemeable from 'material-ui/styles/muiThemeable';
const MyComponent = props => (
   <UsersIcon color={props.muiTheme.palette.primary1Color} />
)
export default muiThemeable()(MyComponent )

from material-ui docs

Upvotes: 3

Hai Nguyen
Hai Nguyen

Reputation: 4059

If your colors don't change at runtime, you can store these constants in a global object that gets used to initialize the theme as well as used in your custom components. This would allow you to not depend on context while keeping your code dry.

Upvotes: 2

Related Questions