0

Created custom Form component which supposed to change its data when child inputs change.

Long story short:

enter image description here

In the current context currentTarget is the form, target is the input which triggered the event. target is exactly what I need - since I can then update the data:

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

Any ideas?

  • Wrong event type?
  • Any way to cast in TypeScript (already tried)?
  • Wrong approach?

EDIT: something like this works, but this is just wrong:

handleChange(e: React.FormEvent) { let foo: any = e; this.setState({ data: { [foo.target.name]: foo.target.value } }); }

0leg
  • 13,464
  • 16
  • 70
  • 94
  • 1
    Have you tried to cast the `e.target` to `(e.target).name`? This is just a long shoot, I didn't tried that. – dlcardozo Mar 08 '18 at 17:20
  • 1
    It was the right way of thinking. Posted the solution - it seems to do the same but in TypeScript. – 0leg Mar 08 '18 at 17:28

3 Answers3

2

After some experimenting:

handleChange(e: React.FormEvent<HTMLFormElement>) { let name: string = (e.target as HTMLFormElement).name; let value: string = (e.target as HTMLFormElement).value; this.setState({ data: { [name]: value } });

It makes sense, since in this case the HTMLInputElement (target) is accessed as HTMLFormElement (listener).

May be there is more elegant solution but this kinda works.

0leg
  • 13,464
  • 16
  • 70
  • 94
  • Also an option to destructure: `const { value }: { value: string } = (event.target as HTMLFormElement).myNameOfInput;` – Remi Feb 14 '20 at 16:15
1

Change the params to handleChange(e: React.FormEvent<HTMLFormElement>) and use e.currentTarget.name.

@thurt explain why in this related SO question, I also found some helpful comments in the type definition file here.

Natalie
  • 331
  • 4
  • 14
0

How do you invoke your function handleChange?

i guess you are doing something like this:

onChange={this.handleChange()}

but you must do it:

onChange={this.handleChange)}

In fact, you have to pass the reference of the function, and not to invoke the function

benjamin Rampon
  • 1,316
  • 11
  • 18