Skip to content

Instantly share code, notes, and snippets.

@huangzhuolin
Last active October 29, 2018 02:10
Show Gist options
  • Save huangzhuolin/ea1ee5c39b097edd6d545f313c06e0cd to your computer and use it in GitHub Desktop.
Save huangzhuolin/ea1ee5c39b097edd6d545f313c06e0cd to your computer and use it in GitHub Desktop.
Use antd to develop form #antd #frontend

Use antd to develop form

Keep UI layer clean

In React, the UI layer means the render function of the page component. Because of the flexibility of React, redundant logic are usually put into the render method, which will easily lead to tremendous render methods. When using antd.Form component, initial values of form fields, form validation, transformation of form values to the UI components' props are all defined in page component. But this may not be a good practice. A clean render method of page component should only concern about the representation logic, for example, the layout of components and user interactions.

To achieve this goal, where to place the initialization, validation of form, and the transformation of form values to components' props need to be taken into account. First, antd form's getFieldDecorator method declare s the behaviour of one field with an configuration object. The object contains initial value of the field, the validating rules, and some tranformation functions connecting form value and the component's prop. We can collect the configurations of all the fields in one place. It can be a file or even a database schema. With this approach, the form will be greater dynamic and easier to maintain. Nevertheless, the page component becomes smaller. Second, complex custom FormItem component can be moved to a single module. If the custom logic is commonly used, this is a good choice. If not, the logic can be implemented using getValueProps and getValueFromEvent in form configuration. This methods can be considered as middleware connecting form fields and UI props.

Some approaches

  1. Seperate styles to .less files using css-module.
  2. If complicated calculation is needed, put the logic into the modal part. Connecting to the result data directly can make UI layer simpler.
  3. If getValueProps and getValueFromEvent methods are used frequently, make reusable custom components.
  4. Extra form configurations to one place.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment