Skip to content

Enable controlled component implementation with formProps #20

@alvinsj

Description

@alvinsj
  1. 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.

  1. 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'}.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions