In my React TypeScript project, I am dynamically creating multiple input controls like TextField, DatePicker, Checkbox, ComboBox etc... in a form like UI. On click on Submit, I want to get the value of each of the input controls. What's an effective way to do this? I can have an onChange event for each of the controls, but I was wondering if there is a better way to do this.
Asked
Active
Viewed 219 times
1 Answers
0
That's not a bad way to do it. You should probably be storing the values in the component's local state (i.e. setState
) or a Redux/Mobx/whatever store if you have that.
That being said, if you have many controls and don't want to adds an individual handler for each one, Fabric components have mostly similar APIs for their onChange
handlers, so you can have a single handler, and add an identifier to the element so that it's easier to store.
Something like:
class MyForm extends React.Component<MyFormProps, MyFormState> {
constructor(props: MyFormProps) {
super(props);
this.state = {
formFields: {...defaultFormValues} // you can imagine having an object of default values
};
}
private _onChangeHandler(ev: React.FormEvent<HTMLElement | HTMLInputElement>, newValue: any) => {
const formFields = {...this.state.formFields};
formFields[ev.target.dataset.id] = newValue;
this.setState({formFields});
}
public render() {
return (
<form>
<TextField data-id="formelem1" onChange={this._onChangeHandler} />
<TextField data-id="formelem2" onChange={this._onChangeHandler} />
<CheckBox data-id="checkbox1" onChange={this._onChangeHandler} />
</form>
);
}
}
Note that the one exception to this is the DatePicker
because its onChange handler (onSelectDate
) receives the new selected date as a single parameter, but you can easily add an if
clause to handle this case.

jake2389
- 1,166
- 8
- 22
-
Thanks for your reply. I am exploring component Refs. Looks promising.. – Putta Mar 06 '20 at 08:30