DEV Community

Cover image for Essential JavaScript Events for React Developers
Iryna Trush
Iryna Trush

Posted on • Edited on

1

Essential JavaScript Events for React Developers

Building interactive React applications relies heavily on understanding how to handle user interactions. React offers a built-in event system, but it’s essential to understand that these events are ultimately based on standard JavaScript DOM events.
Here is a list of seven essential JavaScript events that every React developer should know:

*Code snippets are written in React and TypeScript.


1. onClick

  • Purpose: Triggers when an element is clicked.
  • Usage: Commonly used for buttons, links, and other clickable elements to handle user actions like form submissions, opening modals, etc.

<button onClick={handleClick}> Click Me </button>

const handleClick = () => {
  console.log("Button clicked!");
};

Enter fullscreen mode Exit fullscreen mode

2. onChange

  • Purpose: Triggered when the value of an input element changes.
  • Usage: Essential for form inputs to update the component's state as the user types.


import { useState } from "react";

function MyComponent() {
  const [inputValue, setInputValue] = useState(""); // Define state for input value

  const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setInputValue(event.target.value); // Update the state with the new input value
  };

  return (
    <input
      type="text"
      value={inputValue}
      onChange={handleInputChange} // Handle the change event
    />
  );
}

export default MyComponent;


Enter fullscreen mode Exit fullscreen mode

Note the use of React.ChangeEvent in the handleInputChange function.
Using the correct event type is crucial for handling events properly in TypeScript. Here are some of the most common event types:

  • React.ChangeEvent for onChange on input elements.
  • React.FormEvent for onSubmit on forms.
  • React.KeyboardEvent for onKeyDown on input elements.
  • React.MouseEvent for onMouseEnter and onMouseLeave on div elements.

3. onBlur

  • Purpose: Triggers when an element loses focus.
  • Usage: Often used for form validation after the user moves away from an input field.
<input type="text" onBlur={handleBlur} />

const handleBlur = () => {
  console.log("Input lost focus");
};

Enter fullscreen mode Exit fullscreen mode

4. onFocus

  • Purpose: Triggers when an element gains focus.
  • Usage: Useful for actions when an input field is focused, like showing a tooltip or highlighting the field.
<input type="text" onFocus={handleFocus} />

const handleFocus = () => {
  console.log("Input gained focus");
};

Enter fullscreen mode Exit fullscreen mode

5. onSubmit

  • Purpose: Triggers when a form is submitted.
  • Usage: Handles form submissions, typically preventing the default form submission behavior to process it with JavaScript.
  • Important: The onSubmit event should always be attached to the element, not the submit button. This ensures correct handling regardless of whether the user clicks the submit button or presses Enter. The button element has type="submit", which triggers the form's onSubmit event when clicked.
<form onSubmit={handleSubmit}>
  <input type="text" value={inputValue} onChange={handleInputChange} />
  <button type="submit"> Submit </button>
</form>

const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
  event.preventDefault();
  console.log("Form submitted");
};
Enter fullscreen mode Exit fullscreen mode

6. onKeyDown

  • Purpose: Triggers when a key is pressed down.
  • Usage: Handles keyboard events, such as submitting a form when the Enter key is pressed.
<input type="text" onKeyDown={handleKeyDown} />

const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
  if (event.key === "Enter") {
    console.log("Enter key pressed");
  }
};

Enter fullscreen mode Exit fullscreen mode

7. onMouseEnter and onMouseLeave

  • Purpose: Triggers when the mouse pointer enters or leaves an element.
  • Usage: Handles hover effects, like showing a tooltip or changing an element's style.
<div onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave}>
  Hover over me
</div>

const handleMouseEnter = () => {
  console.log("Mouse entered");
};

const handleMouseLeave = () => {
  console.log("Mouse left");
};

Enter fullscreen mode Exit fullscreen mode

Understanding these JavaScript events enables you to build dynamic and responsive React applications. Effective event handling enhances user experience, optimizes performance, and simplifies debugging. Start using these events in your projects and see the difference!


Building a language learning app and need an API? Read How to use Free dictionary API

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay