Published on

Material-UI Dynamically Changing Styling By Changing Property in Classes

Authors

Today I had to change some React code where in the given piece of code material-ui was used. One thing I struggled with is working out how to programmatically change the specific class of a specific element in a component. For example with the tab component I wanted to be able to dynamically specify what the selected class should be. The documentation for the CSS API section for this keeps mentioning "Styles applied to..." which is a little misleading as the value you actually are meant to assign is a class name. More specifically this class name needs to tie in with the classes you specified in you const styles = {...} declaration. For example in the below I have my styles defined:

const styles = theme => ({
  root: {
    backgroundColor: theme.palette.background.paper,
    width: 500,
  },
  mySelectedA: {
    color: blue;
  },
  mySelectedB: {
    color: red;
  },

});

Now further down I want to use mySelectedA or mySelectedB dynamically based on code:

class YourComponent extends React.Component {

const styles = theme => ({
  root: {
    backgroundColor: theme.palette.background.paper,
    width: 500,
  },
  mySelectedA: {
    color: blue;
  },
  mySelectedB: {
    color: red;
  },

});

render() {
    const { classes, theme } = this.props;
    // ... logic for someCondition
    const classToUse = someCondition ? "mySelectedA" : "mySelectedB";
    //...
 return (
      <div className={classes.root}>
          <Tabs>
            <Tab label="Item One" classes ={{ selected: classes[classToUse]}} />
          </Tabs>
      </div>
    );
  }

}

export default withStyles(styles, { withTheme: true })(YourComponent);

Material-UI creates CSS classes for what you define in styles and put in withStyles when it renders the component. As the class is generated by Material-UI you need to refer to it using the classes prop using the name of the class as you defined it in the styles constant.