Run a Function On Enter in NextJS

Users have expectations when they’re using your tools. Maybe you have a message app? Your enter button should probably send your message. Tab might make you switch windows or menus. We’ll cover how to run a function when your user hits the enter button in a NextJS application. This will also work for any generic React application.

My Setup

Python 3.x
Webstorm
NextJS 13.4.0

Setting Up The Problem

Here’s what my custom component looks like without function execution. In just an input wrapped in a div. I like to keep these under a components folder like mention on line 1 in the code snippet below.

// components/CustomInput/index.tsx
const CustomInput = () => {

  return (
    <div>
      <input
        type={"text"}
        onKeyDown={() => {console.log("stuff is happening")}}
      />
    </div>
  );
};

export default CustomInput;

I’ll give a little more context on my use case. I have a game where users need to input player names. There’s no limit to the number of players they can add. Users might be players with 10+ people so it’s key that inputting names is not a pain. To make the name input workflow smoother I’m letting them add a new user input field to the screen with the enter button.

Run A Function on Enter In NextJS

Now we’ll need to do something when the enter key gets clicked. Let’s use the onKeyDown input parameter to do something every time the users hits a key. If you throw the code above into a NextJS application, you’ll be able to see the message logged in your console for every key click. Now we’ll need to filter those key clicks to only enter.

const CustomInput = () => {
  const onKeyDown = (e) => {
    if(e.key == 'Enter'){
        console.log("You hit enter.")
      }
  }
  return (
    <div>
      <input
        type={"text"}
        onKeyDown={
            (e) => {
                onKeyDown(e);
            }
        }
      />
    </div>
  );
};

export default CustomInput;

You’ll see we are passing the function e above. E represents event data. So e will holds what key is being hit. We can filter that key information in the function execution. Here’s the function that is passed to the input and filters the keys to only take action on enter.

 const onKeyDown = (e) => {
    if(e.key == 'Enter'){
        console.log("You hit enter.")
      }
  }

You should be able to repurpose this to run a function on the clicking of any key in NextJS and React in general. Check out this article if you want more NextJS practice.

Exit mobile version