Skip to content
Advertisement

TypeScript & React – one onChange Handler for multiple input fields

Say I have a form with multiple input fields. In normal ES6/React I would create a single method that all input fields would point their onChange handlers to. Something like this:

handleChange(e) {
    e.preventDefault();
    this.setState({[e.target.name]: e.target.value});
}

This helps in the case where you have a lot of form elements and don’t have to create a specific method to handle each of them.

Is this possible in TypeScript? Even if it is not type-safe?

Advertisement

Answer

As answered in the comments, everything you can do in JavaScript is also valid TypeScript.

However, I guess you’re getting errors from the TypeScript compiler (depending on the compiler options you’ve set).

Assuming your component looks something like this:

interface ComponentProps { }
interface ComponentState {
  name: string
  address: string
}

class MyComponent extends React.Component<ComponentProps, ComponentState> {
  handleChange(e) {
    e.preventDefault()
    this.setState({ [e.target.name]: e.target.value })
  }
}

I’m getting this error:

== External: (30,19): error TS2345: Argument of type ‘{ [x: number]: any; }’ is not assignable to parameter of type ‘ComponentState’.

== External: Property ‘name’ is missing in type ‘{ [x: number]: any; }’.

And when using the noImplicitAny compiler option (which I like to use), this additional error:

== External: (28,16): error TS7006: Parameter ‘e’ implicitly has an ‘any’ type.

If you’re sure that your code is correct, you can silence these errors by explicitly casting the parameter for handleChange and the argument for setState

  handleChange(e: any) {
    e.preventDefault()
    this.setState({ [e.target.name]: e.target.value } as ComponentState)
  }
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement