A
Anonymous

File Upload Schema - Copy this React, Tailwind Component to your project

Import React, { useState } from "react"; import { useForm, Controller } from "react hook form"; import { z } from "zod"; import { zodResolver } from "@hookform/resolvers/zod"; import { useDropzone } from "react dropzone"; // Define Zod schema for validation const schema = z.object({ file: z .custom<File[]>((value) => value && value.length > 0, { message: "File is required", }) .refine( (files) => files.length === 1 && ["image/jpeg", "image/png"].includes(files[0].type), { message: "Only JPEG or PNG files are allowed", } ) .refine((files) => files[0].size <= 5 * 1024 * 1024, { message: "File size must not exceed 5MB", }), }); export default function FileUploadWithPreview() { const [preview, setPreview] = useState(null); // State for preview const { control, handleSubmit, setValue, formState: { errors }, } = useForm({ resolver: zodResolver(schema), }); const onSubmit = (data) => { console.log("File uploaded:", data.file[0]); }; const onDrop = (acceptedFiles) => { setValue("file", acceptedFiles, { shouldValidate: true }); const file = acceptedFiles[0]; setPreview(URL.createObjectURL(file)); // Generate preview URL }; const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop, accept: { "image/jpeg": [".jpeg", ".jpg"], "image/png": [".png"], }, maxFiles: 1, maxSize: 5 * 1024 * 1024, // 5MB }); return ( <form onSubmit={handleSubmit(onSubmit)}> <div> <label>Upload File:</label> <div {...getRootProps()} style={{ border: "2px dashed #ccc", padding: "20px", textAlign: "center", cursor: "pointer", backgroundColor: isDragActive ? "#f0f0f0" : "#fff", }} > <input {...getInputProps()} /> {isDragActive ? ( <p>Drop the file here...</p> ) : ( <p>Drag & drop a file here, or click to select one</p> )} </div> <Controller name="file" control={control} defaultValue={[]} render={({ field }) => null} // Managed by Dropzone /> {errors.file && <p style={{ color: "red" }}>{errors.file.message}</p>} </div> {/* File Preview */} {preview && ( <div style={{ marginTop: "20px", textAlign: "center" }}> <p>Preview:</p> <img src={preview} alt="File Preview" style={{ maxWidth: "200px", maxHeight: "200px", objectFit: "cover" }} /> </div> )} <button type="submit" style={{ marginTop: "20px" }}> Upload </button> </form> ); }

Prompt
Component Preview

About

FileUploadSchema - Effortlessly upload and preview JPEG/PNG files with validation. Built with React and Tailwind. Free code available!

Share

Last updated 1 month ago