Next.js Discord

Discord Forum

properly divide into reusable component and type annotate react-hook-form question

Unanswered
American Chinchilla posted this in #help-forum
Open in Discord
American ChinchillaOP
this is the example form using shadcn and react form hook
"use client"

// imports

const FormSchema = z.object({
  welcomeChannel: z.string()
})

export default function WelcomeForm() {
  const form = useForm<z.infer<typeof FormSchema>>({
    resolver: zodResolver(FormSchema),
  })

  function onSubmit(data: z.infer<typeof FormSchema>) {
    console.log(data)
  }

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)}>
        <FormField
          control={form.control}
          name="welcomeChannel"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Welcome channel</FormLabel>
              <Select onValueChange={field.onChange} defaultValue={field.value}>
                <FormControl>
                  <SelectTrigger>
                    <SelectValue placeholder="Select a channel" />
                  </SelectTrigger>
                </FormControl>
                <SelectContent>
                  <SelectItem value="123">Channel 1</SelectItem>
                  <SelectItem value="234">Channel 2</SelectItem>
                  <SelectItem value="345">Channel 3</SelectItem>
                </SelectContent>
              </Select>
              <FormDescription>
                The channel where the welcome message will be sent
              </FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />
        <Button type="submit">Save</Button>
      </form>
    </Form>
  )
}
and for example i would like to take out the Select part to another file so i can reuse it


"use client"

import {
  FormControl,
  FormDescription,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"

export default function ChannelSelect({
  field,
}: {
  field: any
}) {
  return (
    <FormItem>
      <FormLabel>Welcome channel</FormLabel>
      <Select onValueChange={field.onChange} defaultValue={field.value}>
        <FormControl>
          <SelectTrigger>
            <SelectValue placeholder="Select a channel" />
          </SelectTrigger>
        </FormControl>
        <SelectContent>
          <SelectItem value="123">Channel 1</SelectItem>
          <SelectItem value="234">Channel 2</SelectItem>
          <SelectItem value="345">Channel 3</SelectItem>
        </SelectContent>
      </Select>
      <FormDescription>
        The channel where the welcome message will be sent
      </FormDescription>
      <FormMessage />
    </FormItem>
  )
}
so i tried this but how would i go about type annotating that?

0 Replies