Author -  Sai gowtham

React - How to add the Classname onHover

In this tutorial, we are going to learn about how to add the clasname to a element on hover in react.

Consider, we have the following component in our react app:

import React from 'react';

function Home(){
    return (
        <div>
          <h1>Welcome to my blog</h1>
        </div>
    )
}

export default Home;

To add the classname of a element on hover, add the onMouseOver and onMouseOut event handler to it and change the classname conditionally whenever a element is hovered.

Here is an example:

import React, { useState } from "react";

function Home() {
  const [active, setActive] = useState(false);

  const handleMouseOver = () => {
    setActive(true);
  };

  const handleMouseOut = () => {
    setActive(false);
  };


  return (
    <div>
       <h1
         onMouseOver={handleMouseOver}
         onMouseOut ={handleMouseOut}
         className={{active ? "container" : "box" }}
       >Welcome to my blog</h1>
    </div>
  );
}

export default Home;

In the example above, we added a handleMouseOver and handleMouseOut event handlers to the onMouseOver, onMouseOut props and state active to the className property.

So, whenever a h1 element is hoverd it runs the handleMouseOver function and changes the active state from false to true and adds the container classname to it.

Whenever a mouse is moved away from the h1 element it adds the box classname to it.

Based on the active state we are changing the h1 element classname using ternary expression.

{{active ? "container" : "box" }}

If active is false it chooses the box class, if its true it chooses the container class.

References

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY