How to avoid onMouseEnter getting triggered every time the child element gets replaced?

46 Views Asked by At

I have the following div:

                <div className="header-right-side-language"
                     onClick={handleCountrySwitch}
                     onMouseEnter={handleHover}
                     onMouseLeave={handleNoHover}
                     style={languageButtonStyle}>
                    {currentCountry === 'US' ?
                        <>
                            <US title="United States"/>
                            <p>EN</p>
                        </>
                        : <>
                            <EG title="Egypt"/>
                            <p>AR</p>
                        </>
                    }
                </div>

and here are the called functions:

const handleCountrySwitch = () => {
        // Toggle between US and EG on click
        setCurrentCountry((prevCountry) => (prevCountry === 'US' ? 'EG' : 'US'));
        setLanguageButtonStyle((prevStyle) => ({ ...prevStyle, opacity: 1 }));
};
const handleHover = () => {
        // Update opacity
        setLanguageButtonStyle((prevStyle) => ({ ...prevStyle, opacity: 0.5 }));
};
const handleNoHover = () => {
        // Update opacity
        setLanguageButtonStyle((prevStyle) => ({ ...prevStyle, opacity: 1 }));
};

Due to the re-rendering of the component when the child element is completely replaced, the onMouseEnter gets re-triggered (only if I am hovering over the or not the

).

1

There are 1 best solutions below

1
Reza Moosavi On

You can implement different hover modes with css:

//styles.css
header-right-side-language{
  opacity: 1;
  //...
}
header-right-side-language:hover{
  opacity: 0.5;
  //...
}

But if you need to handle the style with your state, you should keep in mind that the handleHover button will be called after the mouse enters, and after clicking the button, the opacity value will be equal to one. Now, even though the mouse is on the button, the last opacity value in the languageButtonStyle is the same because the enter event will not happen unless you leave the mouse from the div and return it again:

<div
        className="header-right-side-language"
        onClick={handleCountrySwitch}
        onMouseMove={handleHover}
        onMouseLeave={handleNoHover}
        style={languageButtonStyle}
      >
        {currentCountry === "US" ? (
          <>
            <US title="United States" />
            <p>EN</p>
          </>
        ) : (
          <>
            <EG title="Egypt" />
            <p>AR</p>
          </>
        )}
</div>