ShadCn에서 form 깔기

npx shadcn-ui@latest add form

npx shadcn-ui@latest add input

가 생성되었다.

<aside> 💡 store-modal 안에 form을 작성할 것 이다.

</aside>

사용할 라이브러리

import { useForm } from 'react-hook-form';

const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      name: '',
    },
  });

  const onSubmit = async (values: z.infer<typeof formSchema>) => {
    console.log(values);
    // TODO : Create Store
  };

실제 Form 부분

return (
    <Modal
      title='Create Store'
      description='Add a new store to manage products and categories'
      isOpen={storeModal.isOpen}
      onClose={storeModal.onClose}
    >
      <div>
        <div className='space-y-4 py-2 pb-4'>
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)}>
              <FormField
                control={form.control}
                name='name'
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Name</FormLabel>
                    <FormControl>
                      {/* ...field안에 OnChange, blur, value, name이 들어가있다. */}
                      <Input placeholder='E-Commerce' {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <div className='pt-6 space-x-2 flex items-center justify-end w-full'>
                <Button variant='outline' onClick={storeModal.onClose}>
                  Cancel
                </Button>
                {/* onClick이 아니고 form안에 있는 버튼이므로, onSubmit이 실행된다. */}
                <Button type='submit'>Continue</Button>
              </div>
            </form>
          </Form>
        </div>
      </div>
    </Modal>
  );
}