React Typescript cheatsheet: form elements and onChange event types

Blai Pratdesaba
Blai Pratdesaba
Published in
1 min readJul 30, 2019

--

Quick cheat sheet with all the typings used for React forms. All the form elements events are the type React.ChangeEvent<T> , where T is the HTML Element type. Here’s an example of all the different HTML types

For <input type="text"> the event type is React.ChangeEvent<HTMLInputElement>

const Input = (): JSX.Element => {
const [inputValue, setInputValue] = useState<string>("");
return (
<input
type="text"
value={inputValue}
onChange={(
ev: React.ChangeEvent<HTMLInputElement>,
): void => setInputValue(ev.target.value)}
/>
);
};

For <textarea> is React.ChangeEvent<HTMLTextAreaElement>

const TextArea = (): JSX.Element => {
const [textAreaValue, setTextAreaValue] = useState<string>("");
return (
<textarea
value={textAreaValue}
onChange={(
ev: React.ChangeEvent<HTMLTextAreaElement>,
): void => setTextAreaValue(ev.target.value)}
/>
);
};

The HTML5 slider is an <input type="range"> , sharing the same event as the <input type="text"> , React.ChangeEvent<HTMLInputElement>

As it’s counterpart, the value of ev.target.value will be a string, but the majority of cases we will want to use it to get a number. For that, notice how we’re using a parseInt to cast the string to a number .

const Slider = (): JSX.Element => {
const [sliderValue, setSliderValue] = useState<number>(0);
return (
<input
type="range"
min={0}
max={100}
value={sliderValue}
onChange={(
ev: React.ChangeEvent<HTMLInputElement>,
): void => {
setSliderValue(
parseInt(ev.target.value, 10),
);
}}
/>
);
};

For <select>we use React.ChangeEvent<HTMLInputSelect>

const Select = (): JSX.Element => {
const [selectValue, setSelectValue] = useState<string>(
"optionA",
);
return (
<select
value={selectValue}
onBlur={(
ev: React.ChangeEvent<HTMLSelectElement>,
): void => setSelectValue(ev.target.value)}
>
<option value="optionA">Option A</option>
<option value="optionB">Option B</option>
<option value="optionC">Option C</option>
</select>
);
};

--

--