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.


