2

My project is in SPFX, React/TypeScript/Office UI Fabric. I find that I'm making functions for every text fields for a form I'm making. Is there a function that can handle multiple similar fields, but each text field has it's own unique state.

Example text field function:

private _onReason = (ev: React.FormEvent<HTMLInputElement>, newValue?: string) => {
    this.setState({
      Reason: newValue
    });
  }

and another almost identical one:

private _onPurpose = (ev: React.FormEvent<HTMLInputElement>, newValue?: string) => {
    this.setState({
      Purpose: newValue
    });
  }

My aim is to allow the user to submit the states of these multiple text fields, but just cut down the code.

I've read this but don't know how to implement into my project: https://www.pluralsight.com/guides/handling-multiple-inputs-with-single-onchange-handler-react

I think the one thing preventing me from implementing that pluralsight solution is the fact I'm using MS fabric UI and the React.FormEvent<HTMLInputElement>, NewValue?: string) is not liked by the handler function that I attempted below:

public handleChange (evt: React.FormEvent<HTMLInputElement>, newValue?: string) {
    const value = evt.target.value;
    this.setState({
      ...this.state,
      [evt.target.name]: value
    });
  }

It doesn't like the value at the end of const value... it doesn't like the name at the end of [evt.target.name] either.

UPDATE: After trying something from Peter's link suggestion I can eliminate one of the errors from above, (the value error) but it still gives me the error for [evt.target.name] (name to be exact).

NightTom
  • 418
  • 15
  • 37
  • This might be relevant: https://stackoverflow.com/questions/44321326/property-value-does-not-exist-on-type-eventtarget-in-typescript/44321394 – Peter Collingridge Jan 02 '20 at 15:36
  • The above link suggested by Peter gets me closer but I'm still getting an error with [evt.target.name], it doesn't like name ('property name does not exist on EventTarget') – NightTom Jan 02 '20 at 15:47
  • Yeah looks like a TypeScript issue. I would just give it the type if you're on a time crunch. – ejbee3 Jan 02 '20 at 16:03

1 Answers1

2

Your question is easy to understand and very concise. I also like the link you provided about some context to your problem. I use React hooks and the easiest way I've found to cut down on the code is to use an anonymous function in the attribute of the JSX like so:

<label>
  First name
  <input
    type="text"
    onChange={(e) => {setFirstName(e.target.value)}}
  />
</label>
<p> {firstName} </p>

However, it will look a little different because I am not super comfortable with TypeScript so you need to give a type to the e(event) and the firstName(string), and you are not using React hooks. For you, you will have to deconstruct your state object and you'll have more syntax because you have a larger state with multiple objects. Hope this helps!

ejbee3
  • 62
  • 5