2

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 ?

DᴀʀᴛʜVᴀᴅᴇʀ
  • 7,681
  • 17
  • 73
  • 127

1 Answers1

7

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.

luckongas
  • 1,651
  • 8
  • 17
  • Ya for some reason I'm still getting an error: https://codesandbox.io/s/serene-shannon-52p3l?file=/src/components/Header.js – DᴀʀᴛʜVᴀᴅᴇʀ Jan 14 '21 at 18:03
  • 1
    Right, you cannot use hooks inside callbacks. I've updated the solution on the [link](https://codesandbox.io/s/elastic-violet-p8y6o?file=/src/App.js), my recommendation is to split the component in order to be able to use the hook and get the custom styles for each component. – luckongas Jan 14 '21 at 18:32
  • ah I see now. The docs arent very clear in this area . – DᴀʀᴛʜVᴀᴅᴇʀ Jan 14 '21 at 18:35