E

Event Handling

Properly typed event handlers for forms, inputs, clicks, and other DOM events in React.

Code

typescript
1import React, { useState, FormEvent, ChangeEvent, MouseEvent, KeyboardEvent } from "react";
2
3// Form event handling
4interface LoginFormData {
5 email: string;
6 password: string;
7 rememberMe: boolean;
8}
9
10function LoginForm() {
11 const [formData, setFormData] = useState<LoginFormData>({
12 email: "",
13 password: "",
14 rememberMe: false,
15 });
16 const [errors, setErrors] = useState<Partial<LoginFormData>>({});
17
18 // Generic change handler for inputs
19 const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
20 const { name, value, type, checked } = e.target;
21 setFormData((prev) => ({
22 ...prev,
23 [name]: type === "checkbox" ? checked : value,
24 }));
25 };
26
27 // Form submission
28 const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
29 e.preventDefault();
30 console.log("Submitting:", formData);
31 };
32
33 return (
34 <form onSubmit={handleSubmit}>
35 <input
36 type="email"
37 name="email"
38 value={formData.email}
39 onChange={handleChange}
40 placeholder="Email"
41 />
42 <input
43 type="password"
44 name="password"
45 value={formData.password}
46 onChange={handleChange}
47 placeholder="Password"
48 />
49 <label>
50 <input
51 type="checkbox"
52 name="rememberMe"
53 checked={formData.rememberMe}
54 onChange={handleChange}
55 />
56 Remember me
57 </label>
58 <button type="submit">Login</button>
59 </form>
60 );
61}
62
63// Mouse events with proper typing
64interface ButtonWithContextMenuProps {
65 onAction: (action: string) => void;
66}
67
68function ButtonWithContextMenu({ onAction }: ButtonWithContextMenuProps) {
69 const handleClick = (e: MouseEvent<HTMLButtonElement>) => {
70 console.log(`Clicked at: ${e.clientX}, ${e.clientY}`);
71 onAction("click");
72 };
73
74 const handleContextMenu = (e: MouseEvent<HTMLButtonElement>) => {
75 e.preventDefault();
76 console.log("Right-clicked!");
77 onAction("contextmenu");
78 };
79
80 return (
81 <button onClick={handleClick} onContextMenu={handleContextMenu}>
82 Click or Right-click
83 </button>
84 );
85}
86
87// Keyboard events
88function SearchInput() {
89 const [query, setQuery] = useState("");
90
91 const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
92 if (e.key === "Enter") {
93 console.log("Searching for:", query);
94 }
95 if (e.key === "Escape") {
96 setQuery("");
97 }
98 };
99
100 return (
101 <input
102 type="text"
103 value={query}
104 onChange={(e) => setQuery(e.target.value)}
105 onKeyDown={handleKeyDown}
106 placeholder="Search... (Enter to submit, Escape to clear)"
107 />
108 );
109}
110
111// Select and textarea
112function ProfileForm() {
113 const [bio, setBio] = useState("");
114 const [country, setCountry] = useState("");
115
116 const handleTextareaChange = (e: ChangeEvent<HTMLTextAreaElement>) => {
117 setBio(e.target.value);
118 };
119
120 const handleSelectChange = (e: ChangeEvent<HTMLSelectElement>) => {
121 setCountry(e.target.value);
122 };
123
124 return (
125 <div>
126 <textarea
127 value={bio}
128 onChange={handleTextareaChange}
129 placeholder="Tell us about yourself"
130 maxLength={500}
131 />
132 <p>{bio.length}/500</p>
133
134 <select value={country} onChange={handleSelectChange}>
135 <option value="">Select country</option>
136 <option value="us">United States</option>
137 <option value="uk">United Kingdom</option>
138 <option value="ca">Canada</option>
139 </select>
140 </div>
141 );
142}
143
144export { LoginForm, ButtonWithContextMenu, SearchInput, ProfileForm };

Run this example locally

$ npm install react @types/react