How can I access a hover state in reactjs?

HoverReactjs

Hover Problem Overview


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.

Hover Solutions


Solution 1 - Hover

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.

Solution 2 - Hover

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

Solution 3 - Hover

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

Solution 4 - Hover

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.

Solution 5 - Hover

You can implement your own component logics using those events which stolli and BentOnCoding suggested above, or use the module named react-hover

> if I could have a variable that I could pass to another component that would be awesome.

then you can simply wrap another component

 <ReactHover options={optionsCursorTrueWithMargin}>
  <Trigger type="trigger">
    <TriggerComponent />
  </Trigger>
  <Hover type="hover">
    <HoverComponent />
  </Hover>
</ReactHover>

or your plain HTML:

<ReactHover options={optionsCursorTrueWithMargin}>
  <Trigger type="trigger">
    <h1 style={{ background: '#abbcf1', width: '200px' }}> Hover on me </h1>
  </Trigger>
  <Hover type="hover">
    <h1> I am hover HTML </h1>
  </Hover>
</ReactHover>

demo code here: demo

Solution 6 - Hover

This won't work for OP because they wanted a variable but for those who just want a UI hover effect it's usually easier to stick with CSS.

Below example will reveal a delete button when an item is hovered over:

<div className="revealer">
  <div>
    {itemName}
  </div>
  <div className="hidden">
    <Btn label="Delete"/>
  </div>
</div>


.hidden {
  display: none;
}

.revealer:hover .hidden {
  display: block;
}

Parent div has revealer class. When it's hovered over, it'll reveal the hidden div. Hidden div must be nested inside revealer div.

Solution 7 - Hover

You can try to implement below code. Hover functionality can be acheived with Tooltip. Please refer below code and link for clarity https://mui.com/material-ui/react-tooltip/

import * as React from 'react';
import DeleteIcon from '@mui/icons-material/Delete';
import IconButton from '@mui/material/IconButton';
import Tooltip from '@mui/material/Tooltip';

export default function BasicTooltip() {
    return (
    <Tooltip title="Delete">
      <IconButton>
        <DeleteIcon />
      </IconButton>
    </Tooltip>
    );
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionUsernameView Question on Stackoverflow
Solution 1 - HoverstolliView Answer on Stackoverflow
Solution 2 - HoverBentOnCodingView Answer on Stackoverflow
Solution 3 - HoverRumanView Answer on Stackoverflow
Solution 4 - HoverRishavView Answer on Stackoverflow
Solution 5 - HoverJavaScripterView Answer on Stackoverflow
Solution 6 - Hoveruser3674908View Answer on Stackoverflow
Solution 7 - HoverEklavya SenView Answer on Stackoverflow