Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React JS toggle/ adding a class on hover

I'm using the animate.css library with React and trying to set up a element (button) to pulse when hovered over. Tried to look through the docs and here but can't find a way to achieve this simple task. If anyone has achieved this or found a reference would greatly be appreciated.

class App extends Component {

   constructor(props) {
    super(props);

    this.handleHover = this.handleHover.bind(this);
  }

  handleHover(){
    this.setState({
        isHovered: !this.state.isHovered
    });
  }

  render() {
    const btnClass = this.state.isHovered ? "pulse animated" : "";

    return (
      <div>
        <button className={btnClass} onMouseEnter={this.state.handleHover} onMouseLeave={this.state.handleHover}>Test</button>
      </div>
    );
  }
}

export default App;
like image 773
Fernando B Avatar asked Jun 15 '17 19:06

Fernando B


People also ask

How do you toggle a class on hover?

hover(function () { $("li#rs1"). addClass("active"); //Add the active class to the area is hovered }, function () { $("li#rs1"). addClass("not-active"); }); });

How do you trigger a hover event in React?

We do this by adding onMouseOver to the button element. After declaring that this element has an onMouseEnter event handler, we can choose what function we want to trigger when the cursor hovers over the element. We declare a function called changeBackground above the view part of the React Component.


1 Answers

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>
  )
}
like image 138
Chase DeAnda Avatar answered Sep 22 '22 23:09

Chase DeAnda