reboottime / React-Develpment

Some notes, thought, articles or source code readings aggregated here about React Web development.
0 stars 0 forks source link

[Mantine UI Series] Form, Part I #18

Open reboottime opened 1 year ago

reboottime commented 1 year ago

Introduction

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

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 commented 1 year ago

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 commented 1 year ago

The Form Design

The section covers three topics:

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:

reboottime commented 1 year ago

The Form State and API design


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


  const [touched, setTouched] = useState(initialTouched);
  const [dirty, setDirty] = useState(initialDirty);
  const [values, _setValues] = useState(initialValues);
  const [errors, _setErrors] = useState(filterErrors(initialErrors));

Correspondingly,

// 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 commented 1 year ago

References

  1. react form components from react official doc
  2. react-hook-form, Performant, flexible and extensible forms with easy-to-use validation.
  3. mantine ui form