Building shadcn <Form> components for string arrays?

So I know it uses react-hook-form under the hood, but I'm struggling to figure out the best pattern for building the form for an array. Say I had a form schema like this:
const formSchema = z.object({
socials: z.array(z.string()),
});
const formSchema = z.object({
socials: z.array(z.string()),
});
I want to create multiple <Input /> components that should each correspond to a certain element in the "socials" array, but how would this work using shadcn <Form> components? This doesn't work, it throws an error saying "expected array, received string"
<FormField
control={form.control}
name="socials"
render={({ field }) => (
<FormItem>
<FormLabel className="sr-only">Create post</FormLabel>
<FormControl>
{/* I want these inputs to correspond to each element in the array, how do I achieve this? */}
<Input
{...field}
/>
<Input
{...field}
/>
<Input
{...field}
/>
</FormControl>
<FormDescription className="sr-only">
Paste in your Spotify link
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="socials"
render={({ field }) => (
<FormItem>
<FormLabel className="sr-only">Create post</FormLabel>
<FormControl>
{/* I want these inputs to correspond to each element in the array, how do I achieve this? */}
<Input
{...field}
/>
<Input
{...field}
/>
<Input
{...field}
/>
</FormControl>
<FormDescription className="sr-only">
Paste in your Spotify link
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
3 Replies
dan
dan12mo ago
Performant, flexible and extensible forms with easy-to-use validation.
zendev
zendev12mo ago
Ahh so this is the only way, I was hoping there was a slightly less complex pattern but all good field arrays it is
dan
dan12mo ago
form are complex yay
Want results from more Discord servers?
Add your server