Search code examples
cssreactjsstylescss-in-jsgriffel.js

Griffel - CSS in JS - Cannot overwrite child class rule on parent element hover


I'm using Griffel https://griffel.js.org/ for the first time and I am struggling to achieve this simple thing. By default this button is hidden and when the user hover's over the parent I want to make the child visible.

I am using React so I have this button component inside the parent div.

const styles = useStyles();

<div className={styles.userContainer}>
  <Button className={styles.removeUserButton} />
</div>

CSS:

export const useStyles = makeStyles({
  removeUserButton: {
    display: 'none'
  },
  userContainer: {
    backgroundColor: '#fefefe',
    '&:hover': {
      '& removeUserButton': {
        display: 'inline-block'
      } 
    }
  }
})

I was not sure if it will know what the removeUserButton class is so I also tried by making it variable. So I added:

const removeUserClassName = 'removeUserButton';

on top of the file and then in CSS:

[removeUserClassName]: {
  display: 'none'
},
userContainer: {
  backgroundColor: '#fefefe',
  '&:hover': {
    [`& ${removeUserClassName}`]: {
      display: 'inline-block'
    }
  }
}

But this still does not work. And in case you are wondering I have also tried the first piece of code by adding . before removeUserButton.

Has anyone used Griffel and knows how to handle this? Appreciate any guidance. Thank you!

Here is a sandbox I created: https://codesandbox.io/s/griffel-hover-issue-gwx1sj


Solution

  • The issue is that you are attempting to use a classname that is in your configuration (removeUserClassName). Yet, Griffel uses dynamic class names. So you'll need to use a different selector.

    You can see the nature of the dynamic class names in this playground example.

    Here is a working StackBlitz that uses the button as selector rather than class name and it works fine.

    Here is the code for reference:

    import { makeStyles } from '@griffel/react';
    
    export const useStyles = makeStyles({
      removeUserButton: {
        display: 'none',
      },
      userContainer: {
        width: '150px',
        height: '50px',
        backgroundColor: 'black',
        ':hover': {
          '& button': { display: 'inline-block' },
          backgroundColor: 'blue',
        },
      },
    });