React – How to add the Classname onHover

React – How to add the Classname onHover

In this post we will give you information about React – How to add the Classname onHover. Hear we will give you detail about React – How to add the Classname onHoverAnd how to use it also give you demo for it if it is necessary.

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

Hope this code and post will helped you for implement React – How to add the Classname onHover. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US