- To implement a form with controlled inputs, currently we have to add
onChange in every field props:
const renderField = (name, fieldProps) => {
return <FormField onChange={fieldProps.onChange} />
};
const getFieldProps = (name) => {
return { onChange: (e) => this.setState({ [e.target.name]: e.target.value });
};
<FormWithLayout renderField={renderField} getFieldProps={getFieldProps} {...rest} />
However most of the time, "How onChange is triggered?" often just depends only on the kind of input is used, e.g. <input />, <Typeahead />, <CustomInput />.
So rather than having the repeating onChange from getFieldProps, we can handle them in renderField/FormField. This way we can keep getFieldProps for things that is form-specific, while isolate the renderField/FormField for things that is input-specific.
- Proposal: enable
formProps, and add a universal formProps.onFieldValueChanged
const renderField = (name, fieldProps) => {
return <FormField onChange={e => fieldProps.formProps.onFieldValueChange(name, e)} />
};
const onFieldValueChanged = (name, e) => this.setState({ [name]: e.target.value });
<FormWithLayout renderField={renderField} onFieldValueChanged={onFieldValueChange} {...rest} />
By making use of onFieldValueChanged and passing it through with fieldProps.formProps in renderField, we are able to let the renderField/FormField to handle the event individually.
Thus, this demonstrates the flexibility to add handler that can be delegated/handled by the child fields. other use cases can be handling the form props in child field, e.g. formProps.errors = {name: 'cannot be blank'}.
onChangein every field props:However most of the time, "How
onChangeis triggered?" often just depends only on the kind of input is used, e.g.<input />,<Typeahead />,<CustomInput />.So rather than having the repeating
onChangefromgetFieldProps, we can handle them inrenderField/FormField. This way we can keepgetFieldPropsfor things that is form-specific, while isolate therenderField/FormFieldfor things that is input-specific.formProps, and add a universalformProps.onFieldValueChangedBy making use of
onFieldValueChangedand passing it through withfieldProps.formPropsinrenderField, we are able to let therenderField/FormFieldto handle the event individually.Thus, this demonstrates the flexibility to add handler that can be delegated/handled by the child fields. other use cases can be handling the form props in child field, e.g.
formProps.errors = {name: 'cannot be blank'}.