React JS toggle/ adding a class on hover
You can use the onMouseEnter
and onMouseLeave
events on the component and toggle the class accordingly.
constructor(){
super();
this.state = {
isHovered: false
};
this.handleHover = this.handleHover.bind(this);
}
handleHover(){
this.setState(prevState => ({
isHovered: !prevState.isHovered
}));
}
render(){
const btnClass = this.state.isHovered ? "pulse animated" : "";
return <button className={btnClass} onMouseEnter={this.handleHover} onMouseLeave={this.handleHover}></button>
}
Update 05/07/19: Hooks
import React, { useState } from 'react';
export default function Component () {
const [hovered, setHovered] = useState(false);
const toggleHover = () => setHovered(!hovered);
return (
<button
className={hovered ? 'pulse animated' : ''}
onMouseEnter={toggleHover}
onMouseLeave={toggleHover}
>
</button>
)
}
What about using the css :hover property? This worked way better for me by changing my hover class section in the css file to use :hover instead of react.
I tried using the above suggestions but react didn't seem fast enough to get it so the state would become wrong if the mouse moved slowly over the button.