简体   繁体   中英

How can I get what element is being hovered using react?

I have an unordered list with anchor ( <a> ) tags and I need to apply some style based on what link the mouse is hovering.

Is there a way for me to access the classes of the element that is being hovered?

You can create an Item component that insides manages state to see if the rendered item is being hovered or not with the onMouseEnter and onMouseLeave functions. But since you are trying to modify the styling of the elements for such basic action as being hovered, you should keep with just CSS, targeting the HTML element with :hover selector.

In the first approach every Item component will have that state so then in the style={} you can do style={isHovered ? {background: "red"} : null} style={isHovered ? {background: "red"} : null} supposing you have an isHovered state.

I would recommend you styled-components , they are great.

In ReactJS the events have name like onMouseOver , you can see other events here .

For your case you can write like below:

<a onMouseOver={() => { console.log('hovered') }}> ~~~

If you want to apply a style to an element on hover, use the :hover CSS selector...

 #mydiv:hover { background-color:red; }
 <div id="mydiv">Text to hover on!</div>

If you can change the CSS only to get the style changes you want, that's ideal compared to using code to change the styles. With a 100% CSS solution, there's other advantages....

  • You can have people who only know CSS maintain and update the code.
  • You can disable styles without disabling code.
  • You can update styles without breaking code.
  • A CSS checker will catch issues in a .css file that would be missed if they were encoded in raw JS.

Source:MDN Documentation - :hover

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM