(Enter || Return) Key

So, now that we can tab to our button, we want the user to be able to click the Enter or Return key to simulate a click because what good is tabbing to buttons that you can’t click on?

Let’s build a function that will help us to do just that:

const buildHandleEnterKeyPress = (onClick) => ({ key }) => {

if (key === ‘Enter’) {

onClick();

}

};

There are a few things going on here that may be confusing if you’ve never encountered them before.

This function is a curried function meaning it’s a function that returns a function. I’m not going to go into explaining this in-depth, but if you’re unfamiliar with this concept, I’m going to explain why we need this. In our situation, we want to provide a function to our component that will handle whenever a key is pressed. Since we can assume that we will know what the value of `onClick` is at the time that `buildHandleEnterKeyPress` is invoked, then we can create a function that uses the `onClick` function. This allows us to pass any callback function to `buildHandleEnterKeyPress` and it will execute when a key is pressed while the user is focused on a given element.

So now we can head to our `Button` component and use this function to get our desired result:

const Button = ({ children, onClick }) => (

<div

onClick={ onClick }

onKeyPress={ buildHandleEnterKeyPress(onClick) }

tabIndex={ 0 }

>

{ children }

</div>

);

This is really simple for the developer and really important to the people on the internet who absolutely need to be able to use the keyboard to navigate.