Course contentsShow
← React
Lesson 2355 of 2,39651. TypeScript with React BasicsFree lesson

Typing Input Change Handlers for Different Input Types

Handle onChange for text inputs, checkboxes, and select elements with correct HTMLInputElement and HTMLSelectElement types.

Typing Input Change Handlers for Different Input Types

What you'll learn: How to correctly type onChange handlers for text inputs, checkboxes, and select elements using specific HTML element types.

The Core Problem

React's ChangeEvent is generic—it needs to know which HTML element triggered the change. A text input's event.target.value is always a string, but a checkbox's event.target.checked is a boolean. TypeScript needs different types to give you the right properties and catch mistakes.

Typing by Input Type

For text inputs, textareas, and number inputs, use HTMLInputElement:

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

For checkboxes and radio buttons (also HTMLInputElement), access .checked:

const handleCheckboxChange = (e: React.ChangeEvent<HTMLInputElement>) => {
  const isChecked = e.target.checked; // boolean
  setAccepted(isChecked);
};

For select dropdowns, use HTMLSelectElement:

const handleSelectChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
  const selectedValue = e.target.value; // string
  setCategory(selectedValue);
};

Why This Matters

TypeScript will autocomplete .value for inputs and selects, but .checked only for input elements. Using the wrong type means you'll miss autocomplete or get errors when accessing properties that don't exist on that element type.

Think of it like specifying which tool you're using: a screwdriver and a hammer are both tools, but you need to tell TypeScript which one you're holding so it knows what operations are valid.

Key Takeaway: Match your ChangeEvent generic to the actual HTML element—HTMLInputElement for inputs (text and checkboxes), HTMLSelectElement for selects—to get correct type checking and autocomplete for element-specific properties.