hoc-lap-trinh-14

React Final Form là một thư viện quản lý trạng thái của form trong ứng dụng React. Dưới đây là các bước cơ bản để sử dụng React Final Form cùng với một ví dụ minh họa cho form thêm sản phẩm.

1. Cài đặt

Trước tiên, bạn cần cài đặt React Final Form và Final Form:

npm install react-final-form final-form

2. Tạo Form

Dưới đây là ví dụ về cách tạo form thêm sản phẩm với React Final Form và MUI.

import React from 'react';
import { Form, Field } from 'react-final-form';
import { TextField, Button, Box, Typography } from '@mui/material';

const onSubmit = async (values) => {
  console.log('Form values:', values);
  // Xử lý submit form
};

const validate = (values) => {
  const errors = {};
  if (!values.productName) {
    errors.productName = 'Required';
  }
  if (!values.price) {
    errors.price = 'Required';
  } else if (isNaN(values.price)) {
    errors.price = 'Must be a number';
  }
  if (!values.description) {
    errors.description = 'Required';
  }
  return errors;
};

const ProductForm = () => (
  <Form
    onSubmit={onSubmit}
    validate={validate}
    render={({ handleSubmit, form, submitting, pristine, values }) => (
      <form onSubmit={handleSubmit} noValidate>
        <Box sx={{ '& .MuiTextField-root': { m: 1, width: '25ch' } }}>
          <Typography variant="h6" gutterBottom>
            Thêm Sản Phẩm
          </Typography>
          <Field name="productName">
            {({ input, meta }) => (
              <TextField
                {...input}
                label="Tên sản phẩm"
                variant="outlined"
                error={meta.error && meta.touched}
                helperText={meta.touched && meta.error}
              />
            )}
          </Field>
          <Field name="price">
            {({ input, meta }) => (
              <TextField
                {...input}
                label="Giá"
                variant="outlined"
                error={meta.error && meta.touched}
                helperText={meta.touched && meta.error}
              />
            )}
          </Field>
          <Field name="description">
            {({ input, meta }) => (
              <TextField
                {...input}
                label="Mô tả"
                variant="outlined"
                multiline
                rows={4}
                error={meta.error && meta.touched}
                helperText={meta.touched && meta.error}
              />
            )}
          </Field>
          <Box mt={2}>
            <Button
              type="submit"
              variant="contained"
              color="primary"
              disabled={submitting || pristine}
            >
              Thêm sản phẩm
            </Button>
          </Box>
        </Box>
      </form>
    )}
  />
);

export default ProductForm;

Giải thích

  1. Cài đặt và Import các thư viện cần thiết:
    • react-final-formfinal-form để quản lý form.
    • @mui/material@emotion/* để sử dụng các component của MUI.
  2. Tạo hàm onSubmit:
    • Hàm onSubmit sẽ được gọi khi form được submit.
  3. Tạo hàm validate:
    • Hàm validate dùng để kiểm tra các giá trị của form và trả về các lỗi nếu có.
  4. Tạo component ProductForm:
    • Sử dụng FormField từ React Final Form để tạo form.
    • Sử dụng các component của MUI như TextField, Button, Box, và Typography để tạo giao diện.
  5. Tích hợp React Final Form với MUI:
    • Sử dụng Field để kết nối các input với React Final Form.
    • Sử dụng meta.errormeta.touched để hiển thị lỗi khi cần thiết.

Với hướng dẫn này, bạn có thể tạo một form thêm sản phẩm sử dụng React Final Form và MUI.

By hoadv