hairbo
hairbo

Reputation: 3173

How to pass props to to material-ui styles in a sub-selector

Usual apologies if this is asked and answered...

I've got a stylesheet:

const styles = createStyles({
    root: {background: 'blue', color: 'red'},
    highlightedWrapper: {
        '& $root': {
           background: 'green',
           color: 'black'
        }
    }
})

...which I invoke like this:

const useStyles = makeStyles(kanbanStyles);

...and then reference in my component like this:

const classes = useStyles()

So far, so good. What I'd like to be able to do is pass props into useStyles(), which I'd then reference in the stylesheet. So this works:

const classes = useStyles({color: 'yellow'})

const styles = createStyles({
    root: (props) => { return {background: 'blue', color: props.color}},
    highlightedWrapper: {
        '& $root': {
           background: 'green',
           color: 'black'
        }
    }
})

...but I cannot figure out how to invoke the function inside the sub-selector. Like, this doesn't work for me:

const styles = createStyles({
    root: {background: 'blue', color: props.color},
    highlightedWrapper: {
        '& $root': {
           background: 'green',
           color: (props) => props.color
        }
    }
})

I've tried various permutations of the above syntax, putting it right after hightlightedWrapper:, and right after '& $root':, but nothing has worked.

Help?

Thanks!!

Upvotes: 1

Views: 821

Answers (1)

hairbo
hairbo

Reputation: 3173

Props to @RyanCogswell for the answer, but the issue is that if you're going to use a function for a style, in order to handle dynamic props, you must use a function everywhere that style is referenced. So this will break:

  wrapper: {
    '& $name': {
      color: (props) => (props.color ? props.color : 'blue')
    }
  },
  name: {
    color: 'green'
  }

...but this will work:

  wrapper: {
    '& $name': {
      color: (props) => (props.color ? props.color : 'blue')
    }
  },
  name: {
    color: (props) => 'green'
  }

Notice the (props) => 'green'.

This is a bug that may not get resolved anytime soon: https://github.com/mui-org/material-ui/issues/13672#issuecomment-541118923

Upvotes: 1

Related Questions