- How to do CSS :hover function in JSX ?
- How to do CSS :hover function in JSX ?
- How to Style Hover in React
- How to Style Hover in React
- How to Style Hover in React With CSS External Styling
- How to Style Hover in React With Inline Styling
- Free eBook: Git Essentials
- Conclusion
- How to Change an Element’s Style on Hover in React
- Change element style on hover with inline styling
- Change element style on hover with custom component
- 11 Amazing New JavaScript Features in ES13
How to do CSS :hover function in JSX ?
Example Wrap two paragraphs inside a fragment: Run Example » Elements Must be Closed JSX follows XML rules, and therefore HTML elements must be properly closed. */ a:visited < color: green; >/* mouse over link */ a:hover < color: red; >/* selected link */ a:active < color: yellow; >Try it Yourself » Example Style links with different styles: a.ex1:hover, a.ex1:active < color: red; >a.ex2:hover, a.ex2:active < font-size: 150%; >Try it Yourself » Example Hover over a element to show a element (like a tooltip): div < display: none; >span:hover + div < display: block; >Try it Yourself » Example Show and hide a «dropdown» menu on mouse hover: ul < display: inline; margin: 0; padding: 0; >ul li ul li:hover ul li:hover ul ul li ul < position: absolute; width: 200px; display: none; >ul li ul li < background: #555; display: block; >ul li ul li a
How to do CSS :hover function in 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.
and I would like to add a hover style to it just like we do in css with
What is the correct syntax ?
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.
You can use onMouseEnter onMouseLeave to adjust the state of the component
setButtonHovered(true)> onMouseLeave= setButtonHovered(false)> className= />
import './style.css' .Button:hover
Using react to manage state for a hover animation is way overkill. You shouldn’t need to use javascript for a simple CSS hover. You’re in the browser, use the right tool for the right job, right?
So here I’ll show a couple different ways to approach the same goal:
In my component I import glamor and my styles file:
import < style >from 'glamor'; import styles from '../styles';
And in my styles file, I have something like this:
import < style >from 'glamor'; const styles = < redHoverbutton: style(< backgroundColor: "#aaaaaa", fontSize: "1.1rem", transition: "all ease .5s", ":hover": < backgroundColor: "#ff0000", color: "#ffffff" >>) >; export default styles;
And this makes the hover functionality work via css, like this:
This is a css driven hover effect (with transition if you noticed) but this isn’t inline css. None the less, your style can be crafted in the same file, like this:
let theStyle = style( < backgroundColor: "#aaaaaa",transition: "all ease .5s", ":hover": < cursor: "pointer", backgroundColor: "#ffff9b", color: "#fd0808" >>); return (>Hover me!);
Now, how to get the style and the spread operator onto the same line and inside of the JSX element?
It may not be perfect but it works well and accomplished the same thing as a true inline style and in a similar manner.
const ColorButton = withStyles((theme) => (< root: < //color: theme.palette.getContrastText("#26A69A"), borderColor: '#26A69A', color: '#26A69A', borderWidth: 1, borderStyle: 'solid', fontSize: 30, boxShadow:2, backgroundColor: "white", '&:hover': < backgroundColor: "white", color: 'white', >, '&:disabled': < backgroundColor: "#A7A9AC", >, >, >))(ButtonBase);
How to Style Hover in React
Working with visuals is an excellent way to keep our interface interactive and to capture the user’s attention. Having objects animated on our screen creates a unique experience and increases interactivity.
In this article, we will learn how to style hover in React using CSS, as well as how to do inline hover styling.
Hover is a pseudo-class that simply allows us to add specific styles to make a user aware when their mouse is on and off a specific element. For this article, we’ll use a box:
const App = () => < return ( div> div className="box"> p>Hover me! p> div> div> ); >;
which has this basic styling:
.box < height: 200px; width: 200px; background-color: rgb(0, 191, 255); display: flex; justify-content: center; align-items: center; font-size: 30px; cursor: pointer; >
Essentially, we’ll change the background color to lightblue when the mouse is over the box and then return it to its default style when the mouse is removed.
How to Style Hover in React
There are two approaches to this: external and inline. External involves having a separate CSS file that makes it easy to style for hover, whereas inline styling does not allow us to style with pseudo-class, but we will learn how to style hover in inline CSS by using mouse events in this article.
How to Style Hover in React With CSS External Styling
This is very similar to how HTML and CSS work; all we have to do is give the element a className (not class ) or use the tag as the selector which we would target and then style the hover pseudo class:
.box < height: 200px; width: 200px; background-color: rgb(0, 191, 255); display: flex; justify-content: center; align-items: center; font-size: 30px; cursor: pointer; > .box:hover
All we did was add the :hover pseudo class to the previously styled selector and change any of the properties we wanted to change when the mouse was over the element.
How to Style Hover in React With Inline Styling
By inline styling, we mean styling via the element’s tag, which is accomplished with the style attribute. If we want to convert the preceding code to inline styling:
const App = () => < return ( div> div style= height: '200px', width: '200px', backgroundColor: 'rgb(0, 191, 255)', display: 'flex', justifyContent: 'center', alignItems: 'center', fontSize: '30px', cursor: 'pointer', >> > p>Hover me! p> div> div> ); >;
Having styles like this repeated within our App could make it difficult to read, so we could create a style object if we’re only styling a single object on a page, and there’s no need in creating a file for it:
const App = () => < const boxStyle = < height: '200px', width: '200px', backgroundColor: 'rgb(0, 191, 255)', display: 'flex', justifyContent: 'center', alignItems: 'center', fontSize: '30px', cursor: 'pointer', >; return ( div> div style= > p>Hover me! p> div> div> ); >;
So far, we’ve built our box. To style hover with inline CSS in React, we conditionally set inline styles using a state, as well as the onMouseEnter and onMouseLeave props, which tell us when the mouse is on the element and when it is not:
import < useState >from 'react'; const App = () => < const [isHover, setIsHover] = useState(false); const handleMouseEnter = () => < setIsHover(true); >; const handleMouseLeave = () => < setIsHover(false); >; const boxStyle = < >; return ( div> div style= onMouseEnter= onMouseLeave= > p>Hover me! p> div> div> ); >;
At this point, we can conditionally style any property using the *isHover* state:
const boxStyle = < //. backgroundColor: isHover ? 'lightblue' : 'rgb(0, 191, 255)', >;
So far, we’ve seen how to implement it. Now, let’s break down our code and explain why we used the syntax we did. We began by creating a state that stores a boolean value indicating when hovering occurs ( true ) and otherwise (by default it’s set to false ):
const [isHover, setIsHover] = useState(false);
We then also added two events to the div to help change our state and know when the mouse is on the box and when it’s off the box:
onMouseEnter= onMouseLeave= > p>Hover me! p>
The onMouseEnter event is triggered when the mouse enters the element, while the onMouseLeave event is triggered when it leaves. We assigned a function to each of these events, which we now use to change the state:
const handleMouseEnter = () => < setIsHover(true); >; const handleMouseLeave = () => < setIsHover(false); >;
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
We set the state in each function based on the triggered event. Finally, we can use the state to conditionally style the box not only for backgroundColor , but also for any other style:
const boxStyle = < //. backgroundColor: isHover ? 'lightblue' : 'rgb(0, 191, 255)', color: isHover ? 'red' : 'green', >;
When we put all this together, we are now able to style hover in React with Inline style:
import < useState >from 'react'; const App = () => < const [isHover, setIsHover] = useState(false); const handleMouseEnter = () => < setIsHover(true); >; const handleMouseLeave = () => < setIsHover(false); >; const boxStyle = < height: '200px', width: '200px', display: 'flex', justifyContent: 'center', alignItems: 'center', fontSize: '30px', cursor: 'pointer', backgroundColor: isHover ? 'lightblue' : 'rgb(0, 191, 255)', color: isHover ? 'red' : 'green', >; return ( div> div style= onMouseEnter= onMouseLeave= > p>Hover me! p> div> div> ); >; export default App;
Conclusion
We learned how to style hover in React using both external styling and inline styling in this article. Though inline styling is not recommended, it is useful to understand how it works in case we are prompted to use it.
How to Change an Element’s Style on Hover in React
To change an element’s style on hover in React, set a className on the element, and style its :hover pseudo-class.
App.js Copied!
import './App.css'; export default function App() < return ( Coding Beauty
); >
App.css Copied!
We use the :hover pseudo-class to style an element when the user hovers over it with the mouse pointer.
Change element style on hover with inline styling
We can also change an element’s style on hover using inline styles and the element’s style prop. To do this, we need to create state that will determine whether the hover styles should be applied to the element or not. We also need to add event listeners for the mouseenter and mouseleave and change the state’s value in them.
App.js Copied!
import < useState >from 'react'; export default function App() < const [hover, setHover] = useState(false); const handleMouseEnter = () =>< setHover(true); >; const handleMouseLeave = () => < setHover(false); >; return ( > onMouseEnter= onMouseLeave= > Coding Beauty
); >
We use the useState hook to create the boolean state variable that will determine whether the hover styles should be applied to the element or not. useState returns an array of two values. The first is a variable that stores the state, and the second is a function that updates the state when it is called.
We use the onMouseEnter prop to listen for the mouseenter event to detect when the mouse enters within the element’s bounds.
Note: While we could also listen for the mouseover event to detect hover, this event is triggered on an element and every single one of its ancestor elements in the DOM tree (i.e. it bubbles) and this could cause serious performance problems in deep hierarchies. mouseenter doesn’t bubble so we can use it without worrying about this.
Similarly, we use the onMouseLeave prop to listen for the mouseleave to detect when the mouse leaves the element’s bounds.
We use the ternary operator to conditionally set the style based on the boolean state.
Change element style on hover with custom component
If you frequently use the inline styles approach to change the element’s style on hover, it will be better if you encapsulate the logic into a custom component, so you can reuse it in multiple places in your codebase and avoid unnecessary duplication.
Here’s what such a component would like:
Hover.jsx Copied!
import < useState >from 'react'; export default function Hover(< children >) < const [hover, setHover] = useState(); const handleMouseEnter = () =>< setHover(true); >; const handleMouseLeave = () => < setHover(false); >; return ( > onMouseEnter= onMouseLeave= > ); > The Hover component takes a callback function as its child. It passes the state variable storing the hover state to this callback so that you can use it to change the style of the element returned from the callback. Hover calls the callback to render this element.
It wraps the element with a div , on which it listens for the mouseenter and mouseleave events to update the state variable. We set the display CSS property to contents on the wrapper because it plays no visual role on the page. It’s only there for the hover detection.
Here’s how we can use our custom Hover component.

Hover.jsx Copied!
import Hover from './Hover'; export default function App() < return ( ( > > Coding Beauty
)> ); >
11 Amazing New JavaScript Features in ES13
This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.