0

I am trying to write styles for :hover and :focus inside react component. Here is what I have tried.

This is my component

<MyBtn className={classes.authBtn}> This is sample text </MyBtn>

In my styles object, I have tried these following some documents I have found on the web.

authBtn: {
        '&:hover': {
            backgroundColor: '#1565C0'
        }
    }

Next,

'authBtn_hover': {
    backgroundColor: '#1565C0'
}

Next,

authBtn: {
            ':hover': {
                backgroundColor: '#1565C0'
            }
        }
dhanushkac
  • 520
  • 2
  • 8
  • 25
  • Possible duplicate of [css pseudo elements in react](https://stackoverflow.com/questions/28269669/css-pseudo-elements-in-react). (The last answer states that it is impossible, and provides a component that will insert a ` – Kaiido Oct 18 '17 at 03:40
  • @Kaiido :after and :before can be written as inline in the next component. but when it comes to hover, active, focus it has to be written inside the component we are currently refering. – dhanushkac Oct 18 '17 at 03:46
  • Oh and if it's MaterialUI, [this answer](https://stackoverflow.com/a/46121511/3702797) states that it's possible with the `selector{'&:pseudo-class':{rule}}` syntax. Are you sure `authBtn` is a correct selector thought? Shouldn't it be `'.authBtn'`? – Kaiido Oct 18 '17 at 03:47
  • I was pointing you to the [4th answer](https://stackoverflow.com/a/39383482/3702797), which is not only about pseudo-elements but also about pseudo-classes. – Kaiido Oct 18 '17 at 03:48
  • Here it is need to add the class name to the component as below. `` I tried your suggestion like this. still no luck. `authBtn: { '&:hover': { backgroundColor: 'red' } }` – dhanushkac Oct 18 '17 at 03:54

2 Answers2

0

The issue was with the css styling. Rules I have tried overidden by the component inline css. so hover is also not worked. I have added important to the rule and it works correctly. here is the corrected code. Thank you for your support.

authBtn: {
    backgroundColor: '#1565C0',
    '&:hover': {
        backgroundColor: '#0D47A1 !important',
    }
}
dhanushkac
  • 520
  • 2
  • 8
  • 25
0

I have faced this problem before, and I solved it using Radium

This allows you to have styles defined as JS object, but it does support semi-states like hover. It comes with bunch of other helpful features

https://github.com/FormidableLabs/radium

Adam
  • 3,415
  • 4
  • 30
  • 49