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.
Before you jump in, you can also learn how to code with gpteach.us AI that pitch you coding tasks to gain your 10,000 hours code-writing-skills and land your dream job.
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;
In this example:
- We import
ChangeEvent
from'react'
, which represents the type of the change event. - The
handleApartmentMenuOnChange
function takes an event object of typeChangeEvent<HTMLSelectElement>
, whereHTMLSelectElement
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.
Lior Amsalem embarked on his software engineering journey in the early 2000s, Diving into Pascal with a keen interest in creating, developing, and working on new technologies. Transitioning from his early teenage years as a freelancer, Lior dedicated countless hours to expanding his knowledge within the software engineering domain. He immersed himself in learning new development languages and technologies such as JavaScript, React, backend, frontend, devops, nextjs, nodejs, mongodb, mysql and all together end to end development, while also gaining insights into business development and idea implementation.
Through his blog, Lior aims to share his interests and entrepreneurial journey, driven by a desire for independence and freedom from traditional 9-5 work constraints.
Leave a Reply