Skip to content

Instantly share code, notes, and snippets.

@lambdaxyzt
Last active February 23, 2022 13:20
Show Gist options
  • Save lambdaxyzt/816c97b24596780fa0f4e3753dcb9881 to your computer and use it in GitHub Desktop.
Save lambdaxyzt/816c97b24596780fa0f4e3753dcb9881 to your computer and use it in GitHub Desktop.
import OnHoverClick from "./OnHoverClick";
function HoverableAndClickable() {
const [activeState, composedEvents] = OnHoverClick(1000,{hover:true,click:false});
return (
<div>
<input {...composedEvents}/>
<h2>{activeState ? "Hovered" : "Not hovered"}</h2>
</div>
);
}
export default HoverableAndClickable;
import { useState, useRef } from "react";
function OnHoverClick(hoverChangedelay,option={}) {
//options (hover: true or false) , (click: true or false)
if (option.hover == undefined) {
option.hover = true;
}
if (option.click == undefined) {
option.click = true;
}
const [activeState, setActiveState] = useState(false);
const timeoutId = useRef(null);
const handleHover = (futureState,event) => {
clearTimeout(timeoutId.current);
// ### if clicked
if(event.type == 'click') {
setActiveState(futureState);
}
// #### if mouseEnter or mouseLeave (hover)
// activeState (2 condition), state (2 condition) 2x2=4 condition
// if "activeState is true" and "futureState is true" so no need to change
// if "activeState is false" and "futureState is true" so :
if (activeState == false && futureState == true) {
setActiveState(true);
}
// if "activeState is false" and "futureState is false" so no need to change
// if "activeState is true" and "futureState is false" so :
if (activeState == true && futureState == false) {
timeoutId.current = setTimeout(() => {
setActiveState(false);
}, hoverChangedelay);
}
};
const composedEvents = {
onMouseEnter: (option.hover ? (event) => handleHover(true,event) : null),
onMouseLeave: (option.hover ? (event) => handleHover(false,event) : null),
onClick : (option.click ? (event) => handleHover(!activeState,event) : null)
};
return [activeState, composedEvents];
}
export default OnHoverClick;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment