Event handlers play a very important role in building interactive and user-friendly web applications. We use event handlers to describe what the application should do in response to user’s actions or input. So, without further ado, let’s talk about most common event handlers in React.
Submit
In React, the submit event occurs when user clicks the submit button in the form. The button should be contained between <form> tags and it should have type ‘submit’. If both of these conditions are satisfied, clicking the button will trigger the submit event. We can use the onSubmit handler to specify what should happen after users submit the form.
This event handler is often used to do things like clear input fields after submit, or redirect users to a different URL after they submit the form. You can learn how to do this here:
https://simplefrontend.com/clear-form-after-submit-in-react/
These are great UX features and will make lives of your users easier. Users will reward you with their attention and continued loyalty to your app.
Click
This is a pretty simple event. The click event fires whenever user clicks an element. Usually it is set on a button, but you can also listen for click events on <span>, <div>, and even paragraph elements.
Click events are useful if you want to perform a certain actions every time user clicks a button. For example, you might want to skip to a certain element whenever user clicks a specific button. Or you might want to display a popup message when users click on a certain element.
onClick event handlers are usually pretty simple. You can write inline event handler in JSX or define a separate event handler outside of JSX code.
Change
Changes in the input field fire the change event. In other words, whenever user enters or deletes a symbol, the change event will fire. React developers often use the onChange event handler to bind input values to state variables.
In React, we often have controlled components, where input values are stored in the state. onChange handler is absolutely necessary to update input values as they change and make sure we have the most recent input.
Keydown
This event fires any time user presses down any key. In practice, you might use the onKeydown event handler to submit the form whenever user clicks Enter button. onKeydown even allows you to specify the key to listen for. For instance, submit the form when user clicks enter. You only need to specify the key code for enter, and the onKeydown handler will fire when user presses down that specific key.
There are a number of other events that allow you to customize what happens when user performs a certain action. Personally I often use events like onMouseEnter to change the appearance of element when user hovers over it, onDoubleClick for special elements where one click is not enough, and so on.
There is also an onSelect handler for <select> elements. It fires whenever user selects one of the options.