DEV Community

Nguyễn Hữu Hiếu
Nguyễn Hữu Hiếu

Posted on

react-hook-form demo

import { Input } from "@/components/ui/input";
import { Controller, useForm } from "react-hook-form";

const UsernameInput: React.FC<{
  value?: string;
  onChange?: (e?: any) => void;
}> = ({ value, onChange }) => {
  console.log("re-render UsernameInput");
  return (
    <div>
      <label>UsernameInput</label>
      <Input type="text" value={value} onChange={onChange} />
    </div>
  );
};

const MobileInput: React.FC<{
  value?: string;
  onChange?: (e?: any) => void;
}> = ({ value, onChange }) => {
  console.log("re-render MobileInput");
  return (
    <div>
      <label>MobileInput</label>
      <Input type="text" value={value} onChange={onChange} />
    </div>
  );
};

const GmailInput: React.FC<{
  value?: string;
  onChange?: (e?: any) => void;
}> = ({ value, onChange }) => {
  console.log("re-render GmailInput");
  return (
    <div>
      <label>GmailInput</label>
      <Input type="text" value={value} onChange={onChange} />
    </div>
  );
};

export const Demo003HookForm = () => {
  const form = useForm({
    defaultValues: {
      username: "",
      mobile: "",
      gmail: "",
    },
  });

  return (
    <div>
      <h2>Demo003HookForm.tsx</h2>
      <Controller
        name="username"
        control={form.control}
        rules={{ required: true }}
        render={({ field }) => (
          <UsernameInput value={field.value} onChange={field.onChange} />
        )}
      />

      <Controller
        name="mobile"
        control={form.control}
        rules={{ required: true }}
        render={({ field }) => (
          <MobileInput value={field.value} onChange={field.onChange} />
        )}
      />

      <Controller
        name="gmail"
        control={form.control}
        rules={{ required: true }}
        render={({ field }) => (
          <GmailInput value={field.value} onChange={field.onChange} />
        )}
      />
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)