brianalbin3
brianalbin3

Reputation: 93

React/Material Hiding an element's child when it is hovered over using withStyles

I want the ListItemSecondaryAction element with the class actions to be hidden when I hover over the ListItem with the class friendsListItem.

I have tried using the decedent selector within styles but it does not work.

const styles = (theme) => ({
  friendsListItem: {
    '&:hover $actions': {
      visibility: 'hidden'
    },
  },
  actions: {},
  iconButton: {},
  moreVertIcon: {},
});
      <List>
          <ListItem button key="Joe" className={classes.friendsListItem}>
              <ListItemSecondaryAction className={classes.actions}>
                <IconButton className={classes.iconButton}>
                  <MoreVertIcon className={classes.moreVertIcon}/>
                </IconButton>
            </ListItemSecondaryAction>
          </ListItem>
      </List>

Entire code pastebin if needed: https://pastebin.com/4neuJRki

I would expect the ListItemSecondaryActions to disappear when I hover over the ListItem, but nothing happend.

Upvotes: 1

Views: 912

Answers (1)

Ryan Cogswell
Ryan Cogswell

Reputation: 81006

When you use ListItemSecondaryAction it changes the structure of the li element in a somewhat surprising fashion.

Without the secondary action you have a structure like the following:

<li class="list-item-classname">
   whatever is in your ListItem
</li>

but with the secondary action you get something more like:

<li class="container-classname">
   <div class="list-item-classname">
      whatever is in your ListItem
   </div>
   <div class="secondary-action-classname">
      whatever is in your secondary action
   </div>
</li>

The important part to notice about the structure above is that the ListItem class is applied to a sibling of the secondary action and not to an ancestor. In order to apply a class to the parent li element, you need to specify the container class.

From https://material-ui.com/api/list-item/#css:

container -- Styles applied to the container element if children includes ListItemSecondaryAction.

Here's the syntax for this:

        <ListItem
          button
          key="Joe"
          classes={{ container: classes.friendsListItem }}
        >

Edit Hide secondary action on hover

Upvotes: 2

Related Questions