Closed Adarsh1999 closed 3 years ago
Hi @Adarsh1999,
Great that you like the project. I built it considering only the onClick
event in mind. However, i would love to have some suggestions on how can we make it dynamically accept the events one wants to use to trigger the dice roll.
hi @avaneeshtripathi , I created this custom hook :
function useKeyPress(targetKey) {
// State for keeping track of whether key is pressed
const [keyPressed, setKeyPressed] = useState(false);
// If pressed key is our target key then set to true
function downHandler({ key }) {
if (key === targetKey) {
setKeyPressed(true);
}
}
// If released key is our target key then set to false
const upHandler = ({ key }) => {
if (key === targetKey) {
setKeyPressed(false);
}
};
// Add event listeners
useEffect(() => {
window.addEventListener('keydown', downHandler);
window.addEventListener('keyup', upHandler);
// Remove event listeners on cleanup
return () => {
window.removeEventListener('keydown', downHandler);
window.removeEventListener('keyup', upHandler);
};
}, []); // Empty array ensures that effect is only run on mount and unmount
return keyPressed;
}
And this can be used as :
const helloPress= useKeyPress('h');
and when returned in jsx:
{helloPress && {happyPress && alert("yo bro")}
So basically when ever you click 'h' can get the alert so I saw a little bit of your code where you call onclick listener and call roll function so there you can add another prop where you can get a key in string and call the above hook.
Hi @Adarsh1999,
Sorry for the delay. I was a bit occupied with other things. Thanks for your suggestion which actually helped me 🙌 to proceed further. I have published a new version v1.1.1 of the package which now accepts a new prop triggers
which accepts an array of key strings + 'click' (for eg. you can pass triggers={[ 'Enter', ' ', 'click' ]} to take care of multiple triggers for dice to roll). It's also updated in the documentation. Here is the codesandbox with the implementation. Let me know if any issues so we can close this issue. Hope this helps you.
Hi, I liked a lot your package and is super useful to me. But in my project I want dice to roll on press of space bar but the dice only rolls when we do mouse click event. So how can I change the event of dice being rolled on mouse click to event in which space bar is pressed or better to me if both can be implemented simultaneously.. Thanks hope you help me..