Comments (2)
@OmarAljoundi Hey Omar, my current code resembles yours closely. The onSubmit function worked perfectly, but there were some issues with certain props like onChange and onBlur not being forwarded.
I ended up made updates to the FormInput component as shown below:
"use client";
import { Control } from "react-hook-form";
import { Input, InputProps } from "@/components/ui/input";
import {
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage
} from "@/components/ui/form";
import { ChangeEvent, FocusEvent, ReactNode } from "react";
export interface FormInputProps extends InputProps {
label: string;
helper?: string | ReactNode;
control?: Control<any>;
onChange?: (event: ChangeEvent<HTMLInputElement>) => void;
onBlur?: (event: FocusEvent<HTMLInputElement>) => void;
onFocus?: (event: FocusEvent<HTMLInputElement>) => void;
}
const FormInput = ({
label,
name,
type,
placeholder,
control,
required,
helper,
onChange,
onBlur,
onFocus
}: FormInputProps) => {
const fieldState = control?.getFieldState(`${name}`);
const hasError = !!fieldState?.error;
const hasErrorMessage = !!fieldState?.error?.message;
return (
<FormField
control={control}
name={name || ""}
render={({ field }) => (
<FormItem>
<FormLabel>
{label}
{required && <span className="text-danger-500">*</span>}
</FormLabel>
<FormControl>
<Input
variant={hasError ? "danger" : "default"}
type={type}
placeholder={placeholder}
{...field}
onChange={(event) => {
if (onChange) onChange(event);
field.onChange(event);
}}
onBlur={(event) => {
if (onBlur) onBlur(event);
field.onBlur();
}}
onFocus={(event) => {
if (onFocus) onFocus(event);
}}
/>
</FormControl>
{!hasErrorMessage && <FormDescription>{helper}</FormDescription>}
<FormMessage className="text-xs font-normal" />
</FormItem>
)}
/>
);
};
export default FormInput;
FYI, I utilized control?: Control<any>;
because of the component's reusability concern.
Thanks
from ui.
You are passing the props to FormInput but you are not using it.
Since you are using typescript lets re-write the code in strong type kinda way:
Try this instead:
LoginForm
'use client'
import { Form } from '@/components/ui/form'
import { zodResolver } from '@hookform/resolvers/zod'
import { useForm } from 'react-hook-form'
import { z } from 'zod'
import { FormInput } from './FormInput'
import { Button } from '@/components/ui/button'
export const LoginSchema = z.object({
email: z.string(),
password: z.string(),
})
const LoginForm = () => {
const form = useForm<z.infer<typeof LoginSchema>>({
resolver: zodResolver(LoginSchema),
defaultValues: {
email: '',
password: '',
},
})
const onSubmit = (data: z.infer<typeof LoginSchema>) => {
//Handle submition result
console.log(data)
}
return (
<div className="p-16 ">
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormInput
control={form.control}
name="email"
label="Email"
type="text"
placeholder="Enter your email"
id="email"
required
/>
<FormInput
control={form.control}
name="password"
label="Password"
type="password"
placeholder="Enter your Password"
id="password"
required
/>
<Button type="submit">Login</Button>
</form>
</Form>
</div>
)
}
export default LoginForm
import { FormControl, FormField, FormItem } from '@/components/ui/form'
import { Input } from '@/components/ui/input'
import { cn } from '@/lib/utils'
import { Control } from 'react-hook-form'
import { LoginSchema } from './LoginForm'
import { z } from 'zod'
interface FormInputProps {
control: Control<z.infer<typeof LoginSchema>>
name: keyof z.infer<typeof LoginSchema>
type: string
required?: boolean
id?: string
label?: string
placeholder?: string
hasError?: boolean
}
export const FormInput = (props: FormInputProps) => {
const { control, name, type, hasError, placeholder, id, required } = props
return (
<FormField
control={control}
name={name}
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
id={id}
required={required}
//variant={hasError ? "danger" : "default"} assuming you have configured variants
className={cn(hasError && 'border-red-500 ring-red-500')} // if you havent configured the variant you can use classes name
type={type}
placeholder={placeholder}
/>
</FormControl>
</FormItem>
)}
/>
)
}
This will insure your props is passed and is being used correctly, here is a screenshot for when submitting the form:
I hope thats help!
from ui.
Related Issues (20)
- [bug]: React 19 forwardRef warnings HOT 4
- [bug]: ComboBox component not working in Shadcn Website HOT 8
- [bug]: Combobox example breaks on https://ui.shadcn.com/docs/components/combobox HOT 1
- [bug]: data-table pagination breaks with React Compiler
- [bug]: ComboBox > Form preview breaks the site. HOT 3
- [bug]: No accordion animation when `value` is controlled via state
- [bug]: Todays date is not showing when not selected. HOT 1
- [bug]: Data Table headless UI redirect not working
- [bug]: FIX( documentation url): fix url in data-table documentation in mdx file
- [bug]: Tutorial missing steps
- [bug]: Calendar focus foreground color wrong when project setup
- Bug : Incorrect Hover Color for ContextMenuContent
- Can't click after a route push or route replace when an onboarding action in a dialog HOT 1
- [bug]: Carousel refreshes a page when it's inside a form HOT 1
- [feat]: Add ranges to Slider component
- [bug]: Error while switching to V0 in Lift Mode HOT 1
- [feat]: Onboarding component HOT 1
- [bug] — TypeError: Cannot redefine property: File
- [bug]: OTP Input DIGITS_AND_CHARS HOT 2
- [bug]: Drawer ScrollArea frezzes swiping on ios
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from ui.