Keyboard Events

In React, you can handle keyboard events using synthetic events provided by React.

Event

Description

onKeyDown

This event occurs when a user presses the key from keyboard.

onKeyPress

This event occurs when a user presses the key from keyboard.

onKeyUp

This event occurs when a user presses and released the key from keyboard.



React Events Reference

When the user interacts with the web application events are fired. That event can be a mouse click, a keypress, or something rare like connecting the battery with a charger. From the developer side, we need to ‘listen’ to such events and then make our application respond accordingly. This is called event handling which provides a dynamic interface to a webpage.

Syntax:

onEvent={function}

Now we will look at certain rules to keep in mind while creating events in React.

  • camelCase Convention: Instead of using lowercase we use camelCase while giving names of the react events. That simply means we write ‘onClick’ instead of ‘onclick’.
  • Pass the event as a function: In React we pass a function enclosed by curly brackets as the event listener or event handler, unlike HTML where we pass the event handler or event listener as a string.
  • Prevent the default event: Just returning false inside the JSX element does not prevent the default behavior in react. Instead, we have to call the ‘preventDefault’ method directly inside the event handler function.

Example : In this example we implemented an onClick Event in it.

Javascript




// App.js
  
import "./App.css"
const App = () => {
    const function1 = (event) => {
        alert("Click Event Fired")
    }
    return (
        <div className="App">
            <h1>w3wiki</h1>
            <button onClick={function1}>
                Click Me!
            </button>
        </div>
    );
}
export default App;


CSS




/*App.css*/
  
.App {
    min-width: 30vw;
    margin: auto;
    text-align: center;
    color: green;
    font-size: 23px;
}
  
button {
    background-color: lightgray;
    height: 50px;
    width: 150px;
    margin: auto;
    border-radius: 6px;
    cursor: pointer;
}


Output:

Similar Reads

The Complete list of Events are listed below:

...

Form Event:

...

Clipboard Events:

Mouse Events:...

Touch Events:

In React, handling form events is a crucial part of creating interactive and dynamic user interfaces....

Pointer Events:

Clipboard events in React allow you to interact with the user’s clipboard, providing a way to handle copy, cut, and paste operations....

UI Events:

In React, you can handle touch events to create touch-friendly and mobile-responsive user interfaces....

Keyboard Events:

Pointer events in React are a set of events that handle different input devices, including mouse, touch, and pen interactions....

Contact Us