Brennan
Brennan

Reputation: 129

Conditionally Rendering Material UI Styles?

Currently building an application for a school project. I am looking to use an inline conditional render (i.e. condition ? expression1 : expression2) to determine what type of user is currently signed in (a doctor or a pharmacist), which is supposed to render the navbar a different color... a simplified version looks something like this...

const useStyles = makeStyles({
  docNav: {
    background: 'linear-gradient(45deg, #F00000 30%, #DC281E 90%)',
  },

  pharmaNav: {
    background: 'linear-gradient(45deg, #0575E6 30%, #021B79 90%)',
  }
});

const Navbar = ({ isPharmacist }) => {
  const classes = useStyles();

    return (
      <AppBar className={classes.pharmaNav} position="static">
        <Toolbar variant="regular">
          <IconButton>
            <GitHubIcon />
          </IconButton>
        </Toolbar>
      </AppBar>
    ); //and then I also have a corresponding check statement with a similar return if the person signed in is a doctor...

So, to conditionally render the AppBar, depending on if isPharmacist is true or not, what may be a simple way to do this??? I tried <AppBar className={isPharmacist ? classes.pharmaNav : classes.docNav }>, but that didn't seem to work. Any help would be very appreciated.

Upvotes: 10

Views: 17792

Answers (2)

Gus
Gus

Reputation: 11

For anyone else coming here, as this has been deprecated by Material-ui v4. You can now use: TSS It works like a charm! :)

Upvotes: 0

Rasuna Khatami
Rasuna Khatami

Reputation: 1071

You can pass props into the first argument of useStyles like so:

const useStyles = makeStyles({
  navbar: {
    background: props => props.isPharmacist
      ? 'linear-gradient(45deg, #0575E6 30%, #021B79 90%)'
      : 'linear-gradient(45deg, #F00000 30%, #DC281E 90%)',
  },
});

const Navbar = (props) => {
  const classes = useStyles(props);

  return <div className={classes.navbar} />
}

Upvotes: 22

Related Questions