Skip to content

Instantly share code, notes, and snippets.

@Joeldorne
Created June 24, 2024 11:39
Show Gist options
  • Select an option

  • Save Joeldorne/9098b30f06c1f2dde301a8301b186fc6 to your computer and use it in GitHub Desktop.

Select an option

Save Joeldorne/9098b30f06c1f2dde301a8301b186fc6 to your computer and use it in GitHub Desktop.
import React from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
// Example JSON schema for form fields
const jsonSchema = {
fields: [
{
name: 'name',
type: 'text',
label: 'Name',
validation: z.string().max(15, { message: 'Name must be 15 characters or less' }).optional(),
},
{
name: 'email',
type: 'email',
label: 'Email',
validation: z.string().email({ message: 'Invalid email address format' }).optional(),
},
{
name: 'password',
type: 'password',
label: 'Password',
validation: z.string().min(6, { message: 'Password must be at least 6 characters' }).optional(),
}
]
};
const SignupForm = () => {
const initialValues = {};
const validationSchema = {};
// Dynamically build initialValues and validationSchema from jsonSchema using Zod
jsonSchema.fields.forEach(field => {
initialValues[field.name] = '';
validationSchema[field.name] = field.validation;
});
const schema = z.object(validationSchema);
const { register, handleSubmit, formState: { errors, isSubmitting } } = useForm({
resolver: zodResolver(schema),
defaultValues: initialValues,
});
const onSubmit = (values) => {
setTimeout(() => {
console.log(values);
}, 400);
};
return (
<form onSubmit={handleSubmit(onSubmit)} className="max-w-md mx-auto">
{jsonSchema.fields.map(field => (
<div key={field.name} className="mb-4">
<label htmlFor={field.name} className="block text-gray-700">{field.label}</label>
<input
{...register(field.name)}
type={field.type}
className={`mt-1 block w-full border border-gray-300 rounded-md ${
errors[field.name] ? 'border-red-500' : ''
}`}
/>
{errors[field.name] && (
<div className="text-red-500 text-sm">{errors[field.name].message}</div>
)}
</div>
))}
<button type="submit" disabled={isSubmitting} className="bg-blue-500 text-white py-2 px-4 rounded">
Submit
</button>
</form>
);
};
export default SignupForm;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment