Juan-man
Juan-man

Reputation: 478

onKeyUp / onKeyDown function when spacebar is clicked

I'm trying to action a function when either a button is clicked or the spacebar is pressed.

I have this working to some degree but it's not how I want it.

Here's my function:

const showText = () => {
    const x = ToughSpellings.toString();
    console.log(x);
}

Here's my button and spacebar actions:

<input type="text" id="one" onKeyUp={showText} />

<button onClick={showText}>Show Next Letter</button>

I cannot work out how to use onKeyUp without an input field. How can I use this function when the user is simply looking at the website?

Upvotes: 1

Views: 692

Answers (1)

juliomalves
juliomalves

Reputation: 50318

Without using an input field, you'd need to setup a document event listener to listen for keyboard events.

You could have the following code in your React component:

const keyDownHandler = (event) => {
    console.log(event.keyCode); // Key UP would return `38`
    // Handle key event here based on `event.keyCode`
};

useEffect(() => {
    document.addEventListener("keydown", keyDownHandler);
    return () => document.removeEventListener("keydown", keyDownHandler);
}, []);

Upvotes: 2

Related Questions