Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Material-UI: Trigger hover effect programmatically

I am rendering the following Material-UI component in my app:

const handleSetActive = _spyOn => {
  linkEl.current.focus();
};

const linkEl = useRef(null);

return (
    <ListItem
      button
      component={SmoothScrollLink}
      to={cutTo}
      spy
      smooth
      offset={(phone ? -theme.mixins.toolbar.minHeightPhone : -theme.mixins.toolbar.minHeightDesktop) - 20}
      duration={500}
      onSetActive={handleSetActive}
      // className={classNames(spyOn === cutTo && classes.hover)}
      ref={linkEl}
      {...other}
    />
)

It is using the react-scroll package which fires onSetActive whenever one scrolls past that particular ListItem.

I would like, in the simplest way possible, to make ListItem (from Material-UI) enable its hover effect when handleSetActive fires.

How would I best accomplish that?

like image 704
Magnus Avatar asked May 27 '19 01:05

Magnus


1 Answers

Here are the portions of the default styles related to the ListItem hover state:

export const styles = theme => ({
  /* Styles applied to the (normally root) `component` element. May be wrapped by a `container`. */
  root: {
    '&$selected, &$selected:hover': {
      backgroundColor: theme.palette.action.selected,
    },
  },
  /* Styles applied to the inner `component` element if `button={true}`. */
  button: {
    transition: theme.transitions.create('background-color', {
      duration: theme.transitions.duration.shortest,
    }),
    '&:hover': {
      textDecoration: 'none',
      backgroundColor: theme.palette.action.hover,
      // Reset on touch devices, it doesn't add specificity
      '@media (hover: none)': {
        backgroundColor: 'transparent',
      },
    },
  },
  /* Styles applied to the root element if `selected={true}`. */
  selected: {},
});

Since in your case you have button={true}, the styling you want can be achieved by a CSS class that applies the following:

      textDecoration: 'none',
      backgroundColor: theme.palette.action.hover,

Here's a sandbox that shows using the activeClass property for react-scroll's Link to apply a class with this styling: https://codesandbox.io/s/reactscroll-gppym.

Here's another sandbox using a ref to apply the class directly on the DOM node: https://codesandbox.io/s/reactscroll-using-ref-9w8ki; however you shouldn't use this approach (showing it for learning purposes only) since it does more work (would perform worse) than the activeClass approach and is very brittle since a re-render for other reasons could wipe out the class applied via the DOM.

like image 71
Ryan Cogswell Avatar answered Oct 20 '22 14:10

Ryan Cogswell