How to Style Hover in React

How to Style Hover in React

Introduction

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 {
   background-color: lightblue;
}

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={boxStyle}>
            <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={boxStyle}
            onMouseEnter={handleMouseEnter}
            onMouseLeave={handleMouseLeave}
         >
            <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:

<div
   style={boxStyle}
   onMouseEnter={handleMouseEnter}
   onMouseLeave={handleMouseLeave}
>
   <p>Hover me!</p>
</div>

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={boxStyle}
            onMouseEnter={handleMouseEnter}
            onMouseLeave={handleMouseLeave}
         >
            <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.

Last Updated: July 15th, 2022
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Joel OlawanleAuthor

Frontend Developer & Technical Writer

Getting Started with AWS in Node.js

Build the foundation you'll need to provision, deploy, and run Node.js applications in the AWS cloud. Learn Lambda, EC2, S3, SQS, and more!

Want a remote job?

    © 2013-2022 Stack Abuse. All rights reserved.

    DisclosurePrivacyTerms