How To Define Typescript onChange Event In React

In many cases when we write JSX code, HTML inside a react component and we’ll be using typescript. We’ll find ourself interacting with build in events of the browser. one of those events is known as “HTMLSelectElement” or the event that occurs when a user click on an element inside “option” and “Select” html tags. When user interact with those items, The browser fires event and we want to catch that event (to see what the user pick from the list of options) and perform actions accordingly.

In order to make the event itself accessible via Typescript here’s What we’ll do:

  1. We’ll import changeEvent from react
  2. We’ll use it to assign to the change event function
  3. Than we’ll use “HTMLSelectElement” to define the type of the change event, which is a select HTML element.

Let’s see the code

import React, { ChangeEvent } from 'react';

// Define your component
const YourComponent: React.FC = () => {
  
  // Define the event handler function
  const handleMenuOnChange = (e: ChangeEvent<HTMLSelectElement>) => { // <----- here we assign event to ChangeEvent
    // Your logic here
    console.log(e.target.value); // Example: Log the value of the selected option
  };
  
  // Render your component with the event handler attached
  return (
    <select onChange={handleMenuOnChange}>
      {/* Your select options */}
      <option value="1">one</option>
      <option value="2">two</option>
    </select>
  );
};

export default YourComponent;

In this example:

  • We import ChangeEvent from 'react', which represents the type of the change event.
  • The handleApartmentMenuOnChange function takes an event object of type ChangeEvent<HTMLSelectElement>, where HTMLSelectElement represents the type of the HTML select element.
  • Within the event handler, you can access properties of the event object like e.target.value to get the value of the selected option.

This is one event that help typescript interact with the real case events that the browser fire when user interact with our UI and application.

Leave a Reply

Your email address will not be published. Required fields are marked *

All rights reserved 2024 ©