How to Add a Class on Hover in React js
In this lesson, we will see how to add a class on hover in React js, let's assume that we have a bootstrap card and we want to add a shadow to the card once the user puts the mouse over it.
Add a class on hover in React js
So, to do that use the following code.
import React, { useState } from 'react'
export default function Card() {
const [hovered, setHovered] = useState(false);
const toggleHover = () => setHovered(!hovered);
return (
<div className='container'>
<div className="row my-5">
<div className="col-md-6 mx-auto">
<div
className={`card ${hovered ? 'shadow-sm' : ''}`}
onMouseEnter={toggleHover}
onMouseLeave={toggleHover}>
<div className="card-header">
<h3 className="text-center mt-2">
Card title
</h3>
</div>
<div className="card-body">
<p className="card-text">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Assumenda, eum.
</p>
</div>
</div>
</div>
</div>
</div>
)
}