Top 5 Most Used Event Handling Techniques in React with TypeScript

Top 5 Most Used Event Handling Techniques in React with TypeScript

ยท

6 min read

Event handling is a fundamental part of creating interactive and dynamic user interfaces in React. With the power of TypeScript, developers can benefit from type safety while implementing various event-handling techniques. In this blog, we'll explore the top 5 most commonly used event-handling techniques in React with TypeScript. We'll provide practical examples for each technique, showcasing situations where event handling is either passed as props or defined within the same component.

Buy Me A Coffee

1. onClick Event Handling

The onClick event handler is one of the most widely used in React. It's used to handle click events on elements like buttons, links, and other clickable UI elements.

Example 1: Event Handling Defined in the Same Component

import React from 'react';

function ClickCounter() {
  const [count, setCount] = React.useState(0);

  const handleClick = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Clicked {count} times</p>
      <button onClick={handleClick}>Click me</button>
    </div>
  );
}

Example 2: Event Handling Passed as Props

import React from 'react';

function Button(props: { onClick: () => void }) {
  return <button onClick={props.onClick}>Click me</button>;
}

function ClickCounter() {
  const [count, setCount] = React.useState(0);

  const handleClick = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Clicked {count} times</p>
      <Button onClick={handleClick} />
    </div>
  );
}

2. onChange Event Handling

The onChange event handler is essential for handling changes in input elements, such as text fields and checkboxes.

Example 1: Event Handling Defined in the Same Component

import React from 'react';

function TextInput() {
  const [text, setText] = React.useState('');

  const handleTextChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setText(event.target.value);
  };

  return (
    <input type="text" value={text} onChange={handleTextChange} />
  );
}

Example 2: Event Handling Passed as Props

import React from 'react';

function Input(props: { value: string; onChange: (value: string) => void }) {
  return <input type="text" value={props.value} onChange={(e) => props.onChange(e.target.value)} />;
}

function TextInput() {
  const [text, setText] = React.useState('');

  const handleTextChange = (newText: string) => {
    setText(newText);
  };

  return <Input value={text} onChange={handleTextChange} />;
}

3. onSubmit Event Handling

The onSubmit event handler is commonly used to handle form submissions and prevent default behavior.

Example 1: Event Handling Defined in the Same Component

import React from 'react';

function MyForm() {
  const handleSubmit = (event: React.FormEvent) => {
    event.preventDefault(); // Prevents the default form submission
    // Handle form submission logic here
  };

  return (
    <form onSubmit={handleSubmit}>
      {/* Form fields go here */}
      <button type="submit">Submit</button>
    </form>
  );
}

Example 2: Event Handling Passed as Props

import React from 'react';

function Form(props: { onSubmit: (e: React.FormEvent) => void }) {
  return (
    <form onSubmit={props.onSubmit}>
      {/* Form fields go here */}
      <button type="submit">Submit</button>
    </form>
  );
}

function MyForm() {
  const handleSubmit = (event: React.FormEvent) => {
    event.preventDefault(); // Prevents the default form submission
    // Handle form submission logic here
  };

  return <Form onSubmit={handleSubmit} />;
}

4. onMouseOver and onMouseOut Event Handling

The onMouseOver and onMouseOut event handlers are used to handle mouse hover events, enabling the creation of hover effects on elements.

Example 1: Event Handling Defined in the Same Component

import React, { useState } from 'react';

function HoverEffect() {
  const [isHovered, setIsHovered] = useState(false);

  const handleMouseOver = () => {
    setIsHovered(true);
  };

  const handleMouseOut = () => {
    setIsHovered(false);
  };

  return (
    <div
      onMouseOver={handleMouseOver}
      onMouseOut={handleMouseOut}
      className={isHovered ? 'hovered' : ''}
    >
      Hover me
    </div>
  );
}

Example 2: Event Handling Passed as Props

import React, { useState } from 'react';

function HoverElement(props: { onHover: () => void, onHoverOut: () => void }) {
  const [isHovered, setIsHovered] = useState(false);

  const handleMouseOver = () => {
    setIsHovered(true);
    props.onHover();
  };

  const handleMouseOut = () => {
    setIsHovered(false);
    props.onHoverOut();
  };

  return (
    <div
      onMouseOver={handleMouseOver}
      onMouseOut={handleMouseOut}
      className={isHovered ? 'hovered' : ''}
    >
      Hover me
    </div>
  );
}

function HoverEffect() {
  const handleHover = () => {
    // Handle hover logic
  };

  const handleHoverOut = () => {
    // Handle hover out logic
  };

  return <HoverElement onHover={handleHover} onHoverOut={handleHoverOut} />;
}

5. Custom Event Handling

Sometimes, you may need to create custom event handlers to cater to specific user interactions or complex scenarios. Here's an example of custom event handling:

import React from 'react';

function CustomEventHandling() {
  const handleCustomEvent = () => {
    // Custom event handling logic
  };

  return (
    <div>
      <button onClick={handleCustomEvent}>Custom Event</button>
    </div>
  );
}

In this example, we define a custom event handler handleCustomEvent that is triggered when a button is clicked.

Certainly! Custom event handling can be tailored to specific use cases in your React application. Here are a few more examples of custom event handling in React with TypeScript:

1. Custom Event with Data

You can create custom events that carry data to be used by the event handler. Here's an example of a button that emits a custom event with a message:

import React, { useState } from 'react';

interface CustomEventProps {
  onCustomEvent: (message: string) => void;
}

function CustomEventButton({ onCustomEvent }: CustomEventProps) {
  const handleClick = () => {
    const message = 'Hello, Custom Event!';
    onCustomEvent(message);
  };

  return <button onClick={handleClick}>Fire Custom Event</button>;
}

function CustomEventExample() {
  const handleCustomEvent = (message: string) => {
    console.log(message); // Handle the custom event here
  };

  return (
    <div>
      <CustomEventButton onCustomEvent={handleCustomEvent} />
    </div>
  );
}

In this example, the CustomEventButton component emits a custom event with a message that is passed to the event handler defined in the CustomEventExample component.

2. Custom Event for Modal Control

You can use custom events to control the visibility of modals or dialog boxes. Here's an example:

import React, { useState } from 'react';

interface ModalProps {
  isOpen: boolean;
  onToggleModal: () => void;
}

function Modal({ isOpen, onToggleModal }: ModalProps) {
  if (!isOpen) {
    return null; // Don't render the modal if it's not open
  }

  return (
    <div className="modal">
      <div className="modal-content">
        <button onClick={onToggleModal}>Close</button>
        {/* Modal content */}
      </div>
    </div>
  );
}

function CustomEventModalExample() {
  const [isModalOpen, setIsModalOpen] = useState(false);

  const handleToggleModal = () => {
    setIsModalOpen(!isModalOpen);
  };

  return (
    <div>
      <button onClick={handleToggleModal}>Open Modal</button>
      <Modal isOpen={isModalOpen} onToggleModal={handleToggleModal} />
    </div>
  );
}

In this example, a custom event (onToggleModal) is used to control the visibility of the modal.

3. Custom Event for Global State Management

Custom events can be used for global state management with libraries like Redux or Mobx. Here's a simplified example using a custom event to update a global counter:

import React from 'react';

// Simplified global state (e.g., using Redux)
const initialState = { count: 0 };
const rootReducer = (state = initialState, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return { ...state, count: state.count + 1 };
    case 'DECREMENT':
      return { ...state, count: state.count - 1 };
    default:
      return state;
  }
};

// Custom event dispatcher
const dispatch = (action) => {
  // Dispatch the action to the global state management (e.g., Redux)
  // This is a simplified example; use your state management library's dispatch mechanism
};

function Counter() {
  const handleIncrement = () => {
    dispatch({ type: 'INCREMENT' });
  };

  const handleDecrement = () => {
    dispatch({ type: 'DECREMENT' });
  };

  return (
    <div>
      <p>Count: {/* Get count from global state (e.g., Redux) */}</p>
      <button onClick={handleIncrement}>Increment</button>
      <button onClick={handleDecrement}>Decrement</button>
    </div>
  );
}

In this example, the handleIncrement and handleDecrement functions dispatch actions to update a global state, which can be managed by a state management library like Redux.

Custom event handling can be a powerful tool for creating dynamic and interactive React applications tailored to your specific needs. Whether you're passing data, controlling modals, or managing global states, custom events allow you to extend React's capabilities to address unique requirements in your projects.

In summary, event handling is a crucial aspect of building interactive React applications. React with TypeScript makes it even more robust by providing type safety and clear interfaces for handling events. Whether you define event-handling functions within the same component or pass them as props to child components, these event-handling techniques will empower you to create rich and responsive user interfaces in your React applications.

Buy Me A Coffee

Did you find this article valuable?

Support Revive Coding by becoming a sponsor. Any amount is appreciated!

ย