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
).
You can implement different hover modes with css:
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: