patternjavascriptreactCritical
Typescript: React event types
Viewed 0 times
typescriptreacttypesevent
Problem
What is the correct type for React events?
Initially I just used
So in a simple form like this:
What type do I use here as event type?
More generalised answer for all events would be really appreciated.
Thanks
Initially I just used
any for the sake of simplicity. Now, I am trying to clean things up and avoid use of any completely.So in a simple form like this:
export interface LoginProps {
login: {
[k: string]: string | Function
uname: string
passw: string
logIn: Function
}
}
@inject('login') @observer
export class Login extends Component {
update = (e: React.SyntheticEvent): void => {
this.props.login[e.target.name] = e.target.value
}
submit = (e: any): void => {
this.props.login.logIn()
e.preventDefault()
}
render() {
const { uname, passw } = this.props.login
return (
Submit
)
}
}What type do I use here as event type?
React.SyntheticEvent does not seem to be working as I get an error that name and value do not exist on target.More generalised answer for all events would be really appreciated.
Thanks
Solution
The SyntheticEvent interface is generic:
(Technically the
And the
Also, since your events are caused by an input element you should use the
Should be:
(Note: This answer originally suggested using
interface SyntheticEvent {
...
currentTarget: EventTarget & T;
...
}(Technically the
currentTarget property is on the parent BaseSyntheticEvent type.)And the
currentTarget is an intersection of the generic constraint and EventTarget.Also, since your events are caused by an input element you should use the
ChangeEvent (in definition file, the react docs).Should be:
update = (e: React.ChangeEvent): void => {
this.props.login[e.currentTarget.name] = e.currentTarget.value
}(Note: This answer originally suggested using
React.FormEvent. The discussion in the comments is related to this suggestion, but React.ChangeEvent should be used as shown above.)Code Snippets
interface SyntheticEvent<T> {
...
currentTarget: EventTarget & T;
...
}update = (e: React.ChangeEvent<HTMLInputElement>): void => {
this.props.login[e.currentTarget.name] = e.currentTarget.value
}Context
Stack Overflow Q#42081549, score: 401
Revisions (0)
No revisions yet.