In Material UI how can I dynamically pass down the color to my style?

Viewed 4358

New to React and Material UI I'm stumped how to properly pass down a color dynamically I'm pulling from a JSON file and I'm not finding a good reference in my searches, StackOverflow or in the docs.

Research

Attempt

Given the JSON file:

[
  {
    "label": "Home",
    "href": "/",
    "colorHover": ""
  },
  {
    "label": "Monday",
    "href": "/mon",
    "colorHover": "#35c5bd"
  },
  {
    "label": "Tuesday",
    "href": "/tues",
    "colorHover": "#fa8b25"
  },
  {
    "label": "Wednesday",
    "href": "/wed",
    "colorHover": "#f26531"
  }
]

I bring it into my component and loop through it with:

  const getDrawerChoices = () => {
    return headersData.map(({ label, href, colorHover }) => {
      const colorChange = colorHover === '' ? 'inherit' : colorHover

      return (
        <Link
          {...{
            component: RouterLink,
            to: href,
            color: 'inherit',
            style: { textDecoration: 'none' },
            key: label,
          }}
        >
          <MenuItem className={menuItem.hover(colorChange)}>{label}</MenuItem>
        </Link>
      )
    })
  }

Material UI Styles:

const useStyles = makeStyles(colorChange => ({
  menuItem: {
    '&:hover': {
      backgroundColor: `${colorChange} !important`,
    },
  },
}))

but I'm thrown an error. How can I pass a color value dynamically to useStyles or do I need to do it inline with the ?

1 Answers

You have to create a custom makeStyle passing a prop to every key as follows:

const useStyles = makeStyles({
  root: (props) => ({
    "&:hover": {
      backgroundColor: props.hoverColor
    }
  })
});

I'll leave a sandbox link with what I tested and the link to the docs. Anything else I can do let me know.

Related