score:273
The SyntheticEvent interface is generic:
interface SyntheticEvent<T> {
...
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<HTMLInputElement>): 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.)
score:0
The following have the same type:
let event1: { target: { value: any } };
let event2: { target: HTMLInputElement } };
score:2
For those who are looking for a solution to get an event and store something, in my case a HTML 5 element, on a useState
here's my solution:
const [anchorElement, setAnchorElement] = useState<HTMLButtonElement | null>(null);
const handleMenu = (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) : void => {
setAnchorElement(event.currentTarget);
};
score:7
I have the following in a types.ts
file for html input, select, and textarea:
export type InputChangeEventHandler = React.ChangeEventHandler<HTMLInputElement>
export type TextareaChangeEventHandler = React.ChangeEventHandler<HTMLTextAreaElement>
export type SelectChangeEventHandler = React.ChangeEventHandler<HTMLSelectElement>
Then import them:
import { InputChangeEventHandler } from '../types'
Then use them:
const updateName: InputChangeEventHandler = (event) => {
// Do something with `event.currentTarget.value`
}
const updateBio: TextareaChangeEventHandler = (event) => {
// Do something with `event.currentTarget.value`
}
const updateSize: SelectChangeEventHandler = (event) => {
// Do something with `event.currentTarget.value`
}
Then apply the functions on your markup (replacing ...
with other necessary props):
<input onChange={updateName} ... />
<textarea onChange={updateName} ... />
<select onChange={updateSize} ... >
// ...
</select>
score:11
you can do like this in react
handleEvent = (e: React.SyntheticEvent<EventTarget>) => {
const simpleInput = (e.target as HTMLInputElement).value;
//for simple html input values
const formInput = (e.target as HTMLFormElement).files[0];
//for html form elements
}
score:30
for update: event: React.ChangeEvent
for submit: event: React.FormEvent
for click: event: React.MouseEvent
score:32
I think the simplest way is that:
type InputEvent = React.ChangeEvent<HTMLInputElement>;
type ButtonEvent = React.MouseEvent<HTMLButtonElement>;
update = (e: InputEvent): void => this.props.login[e.target.name] = e.target.value;
submit = (e: ButtonEvent): void => {
this.props.login.logIn();
e.preventDefault();
}
score:41
To combine both Nitzan's and Edwin's answers, I found that something like this works for me:
update = (e: React.FormEvent<EventTarget>): void => {
let target = e.target as HTMLInputElement;
this.props.login[target.name] = target.value;
}
score:52
The problem is not with the Event type, but that the EventTarget interface in typescript only has 3 methods:
interface EventTarget {
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
dispatchEvent(evt: Event): boolean;
removeEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
interface SyntheticEvent {
bubbles: boolean;
cancelable: boolean;
currentTarget: EventTarget;
defaultPrevented: boolean;
eventPhase: number;
isTrusted: boolean;
nativeEvent: Event;
preventDefault(): void;
stopPropagation(): void;
target: EventTarget;
timeStamp: Date;
type: string;
}
So it is correct that name
and value
don't exist on EventTarget. What you need to do is to cast the target to the specific element type with the properties you need. In this case it will be HTMLInputElement
.
update = (e: React.SyntheticEvent): void => {
let target = e.target as HTMLInputElement;
this.props.login[target.name] = target.value;
}
Also for events instead of React.SyntheticEvent, you can also type them as following: Event
, MouseEvent
, KeyboardEvent
...etc, depends on the use case of the handler.
The best way to see all these type definitions is to checkout the .d.ts files from both typescript & react.
Also check out the following link for more explanations: Why is Event.target not Element in Typescript?
Source: stackoverflow.com
Related Query
- React Hooks TypeScript event and state types
- Typescript React event handler types
- Typescript: React event types
- Set types on useState React Hook with TypeScript
- Typescript types for React checkbox events and handlers?
- React event type in Typescript
- React prop types with TypeScript - how to have a function type?
- How to organize types definitions in a React Project w/ Typescript
- React event handlers with Typescript and JSX
- Specify type for file upload event in react typescript
- import Event Types from React (TypeScript)
- React TypeScript get Data Attribute From Click Event
- How to attach drag event handlers to a React component using TypeScript
- React Prop Types vs Typescript
- React Typescript - How add Types to location.state when passed in a Route
- React Typescript element types
- React Typescript element types
- Sending event handlers as props into a React component using TypeScript
- React Typescript event type for both interfaces MouseEvent and TouchEvent
- React TypeScript Input Paste Event
- TypeScript types for React component where prop is an array of objects?
- optional react useState types with jsdoc, typescript checkjs (javascript)
- Creating a Custom Button in React Typescript and add onClick Event
- Typescript React stateless function with generic parameter/return types
- How to use Graphql typescript types in react
- onKeyDown Event in React with TypeScript
- Fixing typescript warnings when inferring react props types from map of string=>type
- React TypeScript | Correct Type for Event Handler Prop
- Dynamic object key with Typescript in React event handler
- How to test with jest and typescript with types a basic react function component
More Query from same tag
- ESlint - Error: Must use import to load ES Module
- Styling the UI Fabric Date Picker Callout
- Mock function is not called in click event while testing with jest and enzyme
- Using useEffect and useContext while fetching data
- How to change the background color of react-bootstrap's switch (part of the Forms component) using Emotion
- How to let CSS Modules import files globally by default?
- I want to store an id to the localStorage each time when a user drag and drops
- Unable to pass prop back to parent component
- Can you pass model attributes from an asp.net model into a reactjs.net component?
- Arrow function into "ordinary" function expression in react component
- Call setState with Click or Escape Key
- How do I create an array of objects in a React class component through a for loop to be mapped in a functional component?
- How to change state by passing parameter to setState()
- Can't print a dict: Uncaught TypeError: Cannot read properties of undefined
- How can I map data from a firestore database in a useEffect hook
- How to make componentWillUnmount work?
- How to integrate loading screen on route change with redux in Next.js
- Objects are not valid as a React child - is my JSON data bad?
- ClojureScript: how to change CodeMirror reactively with Reagent
- render a switch button on in material table when i am editing
- Can not upload image to server fetching PHP from react
- A way to clear react browser history?
- How do I implement protected client routes?
- How to stop subscribing store updates?
- Webpack 2 HMR on Preact App
- Pass variables from custom server to components in NextJS
- How can I inject a common code in components in React
- How to add up the values of a single property in an object array?
- ReactJS: Argument of type '(bullets: never[]) => string[]' is not assignable to parameter of type 'SetStateAction<never[]>'
- React Redux Refresh issue