How To Define Typescript onChange Event In React

lior_amsalem

Lior Amsalem

Posted on March 19, 2024

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:

We’ll import changeEvent from react
We’ll use it to assign to the change event function
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;
Enter fullscreen mode Exit fullscreen mode

more code examples you can find here

💖 💪 🙅 🚩
lior_amsalem
Lior Amsalem

Posted on March 19, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related