Get single number from Shadcn UI slider for form?

I'm using Shadcn UI, React Form, and Zod for my Next.js project. I'm using the slider component on part of the form:
<FormField
control={form.control}
name="limit"
defaultValue={user.limit}
render={({ field }) => (
<FormItem className="grid grid-cols-2 items-center grid-">
<FormLabel>Limit:</FormLabel>
<FormControl>
<>
<div className="flex gap-4">
<Slider
onValueChange={field.onChange}
defaultValue={[field.value]}
max={100}
step={1}
/>
<span>{field.value}</span>
</div>
</>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="limit"
defaultValue={user.limit}
render={({ field }) => (
<FormItem className="grid grid-cols-2 items-center grid-">
<FormLabel>Limit:</FormLabel>
<FormControl>
<>
<div className="flex gap-4">
<Slider
onValueChange={field.onChange}
defaultValue={[field.value]}
max={100}
step={1}
/>
<span>{field.value}</span>
</div>
</>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
But the slider returns an array of values, even though I'm using only a single value. How do I get it to pass only that first array value to field.onChange? I tried onValueChange={field.value[0] => field.onChange}, but that produces an error. I thought to make my own handleFieldChange function to convert the array into a single number, but I couldn't figure out how to get the value back into the form. Can you please help? Thanks in advance!
1 Reply
Daniel J. Lewis
Daniel J. Lewis6mo ago
Got it! I just need to come back to the problem with a fresh mind. The solution was simple! Replace:
onValueChange={field.onChange}
onValueChange={field.onChange}
With:
onValueChange={(v) => field.onChange(v[0])}
onValueChange={(v) => field.onChange(v[0])}