Open In App

How to get the enter key in ReactJS ?

Last Updated : 30 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Let us create a React project and then we will create a UI that takes input from users. Users can interact with the UI and press Enter Key to trigger an event through this. 

Approach:

Enter Key in React JS comes in the KeyDown Event. To get the enter key we check the event to verify which key is pressed from the e.key value. and define the event handler function for executing the corresponding task

Syntax:

<input
onKeyDown={(e) => {
if (e.key === "Enter")
handlerFuntion();
}}
/>

Steps to Create React Application:

Step 1: Initialize the react project using this command in the terminal.

npx create-react-app project_name

Step 2: After creating your react project move into the folder to perform different operations.

cd project_name

Project Structure:

Project_Structure

Example: This example demonstrate the use of onKeyDown event to get the enter key and change the state using setState().

Javascript




// Filename - App.js
  
import React, { Component } from "react";
  
class App extends Component {
    state = {
        message: ""
    };
    render() {
        return (
            <div>
                <p>Enter Your Message and Press Enter:</p>
  
                <input
                    onKeyDown={(e) => {
                        if (e.key === "Enter") {
                            this.setState({ message: e.target.value },
                            () => {
                                alert(this.state.message);
                            });
                        }
                    }}
                    type="text"
                />
            </div>
        );
    }
}
export default App;


Step to run the application: Open the terminal and type the following command.

npm start

Output: Open your browser. It will by default open a tab with localhost running (http://localhost:3000/) and you can see the output shown in the image. Enter your message and press ENTER to see the welcome message.

Detecting Enter Key



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads