Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Mantine UI Series] Form, Part I #18

Open
reboottime opened this issue Jul 31, 2023 · 4 comments
Open

[Mantine UI Series] Form, Part I #18

reboottime opened this issue Jul 31, 2023 · 4 comments

Comments

@reboottime
Copy link
Owner

reboottime commented Jul 31, 2023

Introduction

This article discuss Mantine UI Form component in React. The main topics covered include:

  • Overview of popular form solutions
  • Identifying common needs for form components/solutions
  • Basics of form implementation

Given the fact that form solutions are highly customized based on real-world use cases, our analysis starts with examining usage scenarios.

The best practices are covered in Mantine UI Form Part II

@reboottime
Copy link
Owner Author

reboottime commented Jul 31, 2023

Form Usage Scenarios

Now let's explore some common form usage in frontend development:

  1. Form Input and Validation:
    Users interact with the form by filling in various fields, and we validate these fields based on specific criteria. For instance:

    • Some fields may require matching specific requirements, such as being marked as required or validating an email format, and provide users with corresponding error messages as needed.
    • The form can validate user input either while the user is filling out the form or upon submission.
  2. Form Submission:
    After the user has filled out the form, we submit the form data to our backend services.

  3. Loading Form Initial Data:
    In some cases, we may need to load initial data into the form from backend services.

  4. Manipulate Form Programmatically, for example:

    • Load the value options of a select component based on another form field.
    • Clear error messages if a field is no longer required as its premise field changed.
    • Disable the form submit button if the form is submitting data to the backend service.

@reboottime
Copy link
Owner Author

reboottime commented Jul 31, 2023

The Form Design

The section covers three topics:

  • What are exposed for developer users.
  • What are available for developers to customize the for form behavior and initial state.
  • What are included in the form's state.

Afterward, we will delve into the details of the above points.



What components/hooks are exposed for developer users to use?

The most common pattern for designing highly customized components has two forms:

  • A hook-based API that covers customization/initialization and exposes state management functionalities to developers. For instance:

      function Demo() {
        const form = useForm({
          initialValues: {
            email: '',
            termsOfService: false,
          },
      
          validate: {
            email: (value) => (/^\S+@\S+$/.test(value) ? null : 'Invalid email'),
          },
        });
      
        return (
            <form onSubmit={form.onSubmit((values) => console.log(values))}>
              <TextInput
                withAsterisk
                label="Email"
                placeholder="[email protected]"
                {...form.getInputProps('email')}
              />
      
              <Checkbox
                mt="md"
                label="I agree to sell my privacy"
                {...form.getInputProps('termsOfService', { type: 'checkbox' })}
              />
      
              <Group position="right" mt="md">
                <Button type="submit">Submit</Button>
              </Group>
            </form>
          
          );
        }
  • A component that accepts the state initialization/customization. For instance:

        <Form onSubmit={submit} initialValues={initialValues} validators={validators}>
          {(form) => <>{/**a set of form fields managed by the form**/}</>}
        </Form>;

@reboottime
Copy link
Owner Author

reboottime commented Jul 31, 2023

The Form State and API design


From an end-users' perspective, the key aspects of the form state that we care about are:

  • The form's values that will be submitted to our backend services.
  • The form's errors generated by validating form (field) values, as the form validation errors relies on the form's interaction state, so we have more granular state variables
    • touched: to indicate what fields have been touched by users
    • dirty: to indicate what fields have been changes
  const [touched, setTouched] = useState(initialTouched);
  const [dirty, setDirty] = useState(initialDirty);
  const [values, _setValues] = useState(initialValues);
  const [errors, _setErrors] = useState(filterErrors(initialErrors));

Correspondingly,

  • we expose interfaces that initialize above values for Form and useForm
  • and expose functions that update above state variables programmatically
  • update above state variables based on user's interaction
  • and provide programmers the interface to extend form validation via validate
// The params available to initialize for the form
export function useForm<
 Values = Record<string, unknown>,
 TransformValues extends _TransformValues<Values> = (values: Values) => Values
>({
 initialValues = {} as Values,
 initialErrors = {},
 initialDirty = {},
 initialTouched = {},
 clearInputErrorOnChange = true,
 validateInputOnChange = false,
 validateInputOnBlur = false,
 validate: rules,
}
// The values/functions exposed for the `useForm` hook
return {
    values,
    errors,
    setValues,
    setErrors,
    setFieldValue,
    setFieldError,
    clearFieldError,
    clearErrors,
    reset,
    validate,
    onSubmit,
    onReset,
    isDirty,
    isTouched,
    setTouched,
    setDirty,
    resetTouched,
    resetDirty,
    isValid,
  };

@reboottime reboottime changed the title [Mantine UI Series] Form [Mantine UI Series] Form, Part I Jul 31, 2023
@reboottime reboottime removed the todo label Aug 4, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant