Search code examples
javascriptreactjsfunctionarrow-functions

How can i change my spans state using onMouseHover?


I am currently changing the state of my span by referring to it using document.getElementById('heart').innerHTML = 'favorite';

Is there a better way of doing this? and if so, please share your solution with me. My code is written below.

import React from 'react'

//custom  functions
const heartHover = (e)=>{
    document.getElementById('heart').innerHTML = 'favorite';
}
const heartNotHover = (e)=>{
    document.getElementById('heart').innerHTML = 'favorite_border';
}
const Navbar = () => {
    return (
        <div>
              <span id="heart" onMouseOver={heartHover} onMouseLeave={heartNotHover} class="material-icons">
                            favorite_border
              </span>
                  
        </div>
    )
}

export default Navbar

Solution

  • When you use event listeners you need useEffect + clean them.

    Check this solution : Hide and Show modal on mouseenter and mouseleave using React Hooks

    And this guide : https://www.pluralsight.com/guides/how-to-cleanup-event-listeners-react