116

I have a sidenav with a bunch of basketball teams. So I would like to display something different for each team when one of them is being hovered over. Also, I am using Reactjs so if I could have a variable that I could pass to another component that would be awesome.

Username
  • 1,380
  • 2
  • 9
  • 19
  • possible duplicate of [a hover button in react.js](http://stackoverflow.com/questions/28072196/a-hover-button-in-react-js) – BentOnCoding Aug 20 '15 at 19:07

4 Answers4

192

React components expose all the standard Javascript mouse events in their top-level interface. Of course, you can still use :hover in your CSS, and that may be adequate for some of your needs, but for the more advanced behaviors triggered by a hover you'll need to use the Javascript. So to manage hover interactions, you'll want to use onMouseEnter and onMouseLeave. You then attach them to handlers in your component like so:

<ReactComponent
    onMouseEnter={() => this.someHandler}
    onMouseLeave={() => this.someOtherHandler}
/>

You'll then use some combination of state/props to pass changed state or properties down to your child React components.

Mathyou
  • 532
  • 2
  • 12
  • 26
stolli
  • 4,405
  • 2
  • 22
  • 36
  • okay, I think that will work. let me test it out. also, how can I pass this variable to a different/not connected component? – Username Aug 20 '15 at 19:07
  • 1
    That actually gets tricky, React doesn't exactly provide for that. In the architecture of a web app, that gets into the global, over-arching communication methodology chosen. Many people would choose an event-bus type solution, where some global event manager is posting and receiving events in disparate components. These event messages would contain the data you want to pass as arguments. This is what Facebook suggests in their docs on the topic: https://facebook.github.io/react/tips/communicate-between-components.html – stolli Aug 20 '15 at 19:15
  • 2
    One thing I want to add is that `onMouseEnter` `onMouseLeave` are DOM events. They won't work on a custom `ReactComponent`, you will need to pass the events down as a prop and bind these events to a DOM element in that `ReactComponent`, like `
    this.props.onMouseOver }>`
    – DAMIEN JIANG May 14 '19 at 21:21
36

ReactJs defines the following synthetic events for mouse events:

onClick onContextMenu onDoubleClick onDrag onDragEnd onDragEnter onDragExit
onDragLeave onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave
onMouseMove onMouseOut onMouseOver onMouseUp

As you can see there is no hover event, because browsers do not define a hover event natively.

You will want to add handlers for onMouseEnter and onMouseLeave for hover behavior.

ReactJS Docs - Events

user3687289
  • 103
  • 8
BentOnCoding
  • 23,888
  • 10
  • 59
  • 92
3

For having hover effect you can simply try this code

import React from "react";
  import "./styles.css";

    export default function App() {

      function MouseOver(event) {
        event.target.style.background = 'red';
      }
      function MouseOut(event){
        event.target.style.background="";
      }
      return (
        <div className="App">
          <button onMouseOver={MouseOver} onMouseOut={MouseOut}>Hover over me!</button>
        </div>
      );
    }

Or if you want to handle this situation using useState() hook then you can try this piece of code

import React from "react";
import "./styles.css";


export default function App() {
   let [over,setOver]=React.useState(false);

   let buttonstyle={
    backgroundColor:''
  }

  if(over){
    buttonstyle.backgroundColor="green";
  }
  else{
    buttonstyle.backgroundColor='';
  }

  return (
    <div className="App">
      <button style={buttonstyle}
      onMouseOver={()=>setOver(true)} 
      onMouseOut={()=>setOver(false)}
      >Hover over me!</button>
    </div>
  );
}

Both of the above code will work for hover effect but first procedure is easier to write and understand

Ruman
  • 160
  • 1
  • 4
2

I know the accepted answer is great but for anyone who is looking for a hover like feel you can use setTimeout on mouseover and save the handle in a map (of let's say list ids to setTimeout Handle). On mouseover clear the handle from setTimeout and delete it from the map

onMouseOver={() => this.onMouseOver(someId)}
onMouseOut={() => this.onMouseOut(someId)

And implement the map as follows:

onMouseOver(listId: string) {
  this.setState({
    ... // whatever
  });

  const handle = setTimeout(() => {
    scrollPreviewToComponentId(listId);
  }, 1000); // Replace 1000ms with any time you feel is good enough for your hover action
  this.hoverHandleMap[listId] = handle;
}

onMouseOut(listId: string) {
  this.setState({
    ... // whatever
  });

  const handle = this.hoverHandleMap[listId];
  clearTimeout(handle);
  delete this.hoverHandleMap[listId];
}

And the map is like so,

hoverHandleMap: { [listId: string]: NodeJS.Timeout } = {};

I prefer onMouseOver and onMouseOut because it also applies to all the children in the HTMLElement. If this is not required you may use onMouseEnter and onMouseLeave respectively.

Rishav
  • 3,095
  • 25
  • 45