TypeScript & React – one onChange Handler for multiple input fields Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of TypeScript & React – one onChange Handler for multiple input fields without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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) {
    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?


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) {
    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) {
    this.setState({ [e.target.name]: e.target.value } as ComponentState)
We are here to answer your question about TypeScript & React – one onChange Handler for multiple input fields - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji