Skip to content

Commit 1bc5838

Browse files
authored
shorten React.ChangeEventHandler example and move to discussion
shorten React.ChangeEventHandler example and move to discussion
1 parent d5b7133 commit 1bc5838

File tree

1 file changed

+8
-20
lines changed

1 file changed

+8
-20
lines changed

README.md

Lines changed: 8 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -369,33 +369,21 @@ class App extends React.Component<{}, { // no props
369369
}
370370
```
371371

372-
You can also use React's event handler types like this:
372+
Instead of typing the arguments and return values with `React.FormEvent<>` and `void`, you can may alternatively apply types on to the event handler itself (*contributed by @TomasHubelbauer*):
373373

374374
```tsx
375-
class App extends React.Component<{}, { // no props
376-
text: string,
377-
}> {
378-
state = {
379-
text: ''
380-
}
381-
render() {
382-
return (
383-
<div>
384-
<input
385-
type="text"
386-
value={this.state.text}
387-
onChange={this.onChange}
388-
/>
389-
</div>
390-
);
391-
}
392375
onChange: React.ChangeEventHandler<HTMLInputElement> = (e) => {
393376
this.setState({text: e.currentTarget.value})
394377
}
395-
}
396378
```
397379

398-
[Something to add? File an issue](https://github.com/sw-yx/react-typescript-cheatsheet/issues/new).
380+
<details>
381+
382+
<summary><b>Discussion</b></summary>
383+
384+
Why two ways to do the same thing? The first method uses an inferred method signature `(e: React.FormEvent<HTMLInputElement>): void` and the second method enforces a type of the delegate provided by `@types/react`. So `React.ChangeEventHandler<>` is simply a "blessed" typing by `@types/react`, whereas you can think of the inferred method as more... *artisanally hand-rolled*. Either way it's a good pattern to know. [See our Github PR for more](https://github.com/sw-yx/react-typescript-cheatsheet/pull/24).
385+
386+
</details>
399387

400388
# Section 3: Advanced Guides
401389

0 commit comments

Comments
 (0)