I need to create a button - when the user hovers the button, there is a 50% chance that the button moves in a random direction by 300px, and a 40% chance that it becomes unclickable;
How can I manage this?
I created a function called randomCalc() to calculate the percentages for the actions to happen, and I call this func on onMouseOver; I am calling another function cleanUp() on onMouseLeave. I am also using setState() to manage the state for isHovered, isMoved, isClickable (booleans that I use to control the behavior of the button). I am trying to use onMouseOver and onMouseLeave to set the values for the booleans, but my code is not working properly. In terms of the style, I am trying to make the logic work so I am using a rotation instead of random movement for the btn - if you have a suggestion for a better implementation, I would appreciate it.
//local state
const [isHovered, setIsHovered] = useState(false);
const [isDisabled, setIsDisabled] = useState(false);
const [isMoved, setIsMoved] = useState(false)
//useEffect
useEffect(() => { }, [isHovered]);
//calculating the chances
const randomCalc = () => {
setisHovered(true)
const rand = Math.floor(Math.random() * 100);
if (rand < 50) {
setIsDisabled(true)
setIsMoved(false)
}
else if (rand < 90) {
setIsMoved(true)
setIsDisabled(false)
}
else if (rand < 100) {
setIsDisabled(false)
setIsMoved(false)
}
}
//cleaning up the state back to false for all 3 booleans
const cleanUp = () => {
setIsDisabled(false)
setIsMoved(false)
setisHovered(false)
}
//button
<button
disabled={isDisabled}
onMouseOver={() => randomCalc()}
onMouseLeave={() => cleanUp()}
style={{transform: isMoved ? 'rotate(90deg)' : 'rotate(0deg)'}}
>
Click
</button>