Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do CSS :hover function in JSX ?

Tags:

reactjs

jsx

Hi and thanks for the great job here. I am using react.js for my project to build my components and I feel a little bit stuck in my project right now. I am trying to style a button with a hover function and I don't know how to apply this to react.

Here is the code :

let button = {
    backgroundColor: colorPalette.white,
    border: "1px solid rgb(12,106,145)",
    color: colorPalette.brandCol1,
    textAlign: 'center',
    textDecoration: 'none',
    fontSize : 'inherit',
    fontWeight : 600,
    padding : "5px 8px 5px 8px"
}

and I would like to add a hover style to it just like we do in css with

button:hover {
style here.......
}

What is the correct syntax ?


2 Answers

You can use:

    const styles = {
    myStyleClassName: {
            padding: '16px 0px 16px 0px',
            '& a': {
                textDecoration: 'none',
                color: '#0000ee',
            },
            '& a:hover': {
            textDecoration: 'underline',
        },
    },
    myButtonClass: {
        '&:hover': {
             textDecoration: 'underline',
        },       
    },
};

....

render() {
    <span className={myStyleClassName}><a tag><button><someDomObjct></span>
    <button className={myButtonClass}>my label</button>
}

See: http://cssinjs.org/jss-nested/?v=v6.0.1 The repo isn't necessary for everything, the above should work out of the box.

like image 95
generalG Avatar answered Sep 10 '25 14:09

generalG


You can use onMouseEnter onMouseLeave to adjust the state of the component

<button
  onMouseEnter={() => setButtonHovered(true)} 
  onMouseLeave={() => setButtonHovered(false)}
  className={buttonIsHovered ? 'hover' : null}
/>

see here for more info

or just use a css class?

import './style.css'

<button className="Button"/>

.Button:hover {
  ...
}
like image 26
Tyler Sebastian Avatar answered Sep 10 '25 12:09

Tyler Sebastian