Typescript input onchange event.target.value
Generally event handlers should use e.currentTarget.value
, e.g.:
onChange = (e: React.FormEvent<HTMLInputElement>) => { const newValue = e.currentTarget.value;}
You can read why it so here (Revert "Make SyntheticEvent.target generic, not SyntheticEvent.currentTarget.").
UPD: As mentioned by @roger-gusmao ChangeEvent
more suitable for typing form events.
onChange = (e: React.ChangeEvent<HTMLInputElement>)=> { const newValue = e.target.value;}
the correct way to use in TypeScript is
handleChange(e: React.ChangeEvent<HTMLInputElement>) { // No longer need to cast to any - hooray for react! this.setState({temperature: e.target.value}); } render() { ... <input value={temperature} onChange={this.handleChange} /> ... ); }
Follow the complete class, it's better to understand:
import * as React from "react";const scaleNames = { c: 'Celsius', f: 'Fahrenheit'};interface TemperatureState { temperature: string;}interface TemperatureProps { scale: string;}class TemperatureInput extends React.Component<TemperatureProps, TemperatureState> { constructor(props: TemperatureProps) { super(props); this.handleChange = this.handleChange.bind(this); this.state = {temperature: ''}; } // handleChange(e: { target: { value: string; }; }) { // this.setState({temperature: e.target.value}); // } handleChange(e: React.ChangeEvent<HTMLInputElement>) { // No longer need to cast to any - hooray for react! this.setState({temperature: e.target.value}); } render() { const temperature = this.state.temperature; const scale = this.props.scale; return ( <fieldset> <legend>Enter temperature in {scaleNames[scale]}:</legend> <input value={temperature} onChange={this.handleChange} /> </fieldset> ); }}export default TemperatureInput;
You can do the following:
import { ChangeEvent } from 'react';const onChange = (e: ChangeEvent<HTMLInputElement>)=> { const newValue = e.target.value;}