AutorÃa | Ultima modificación | Ver Log |
import React, { useState } from 'react';import { useFormContext } from 'react-hook-form';import { Button, IconButton, Box, Typography } from '@mui/material';import { styled } from '@mui/material/styles';import PhotoCamera from '@mui/icons-material/PhotoCamera';import DeleteIcon from '@mui/icons-material/Delete';const VisuallyHiddenInput = styled('input')({clip: 'rect(0 0 0 0)',clipPath: 'inset(50%)',height: 1,overflow: 'hidden',position: 'absolute',bottom: 0,left: 0,whiteSpace: 'nowrap',width: 1});export function FormImagePicker({ name, label, ...rest }) {const {register,setValue,watch,formState: { errors }} = useFormContext();const [previewImage, setPreviewImage] = useState(null);const watchedImage = watch(name);const handleChange = (event) => {const file = event.target.files?.[0];if (file) {setValue(name, file);const reader = new FileReader();reader.onloadend = () => {setPreviewImage(reader.result);};reader.readAsDataURL(file);}};const handleRemove = () => {setValue(name, null);setPreviewImage(null);};return (<Box sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}><Typography component='label' htmlFor={name} sx={{ display: 'block', mb: 1 }}>{label}</Typography><Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}><Button component='label' variant='outlined' startIcon={<PhotoCamera />}>Subir Imagen<VisuallyHiddenInputid={name}name={name}type='file'onChange={handleChange}{...register(name)}{...rest}/></Button>{previewImage && (<Box sx={{ position: 'relative' }}><imgsrc={previewImage}alt='Vista previa'style={{ height: 100, width: 100, objectFit: 'cover' }}/><IconButtonaria-label='eliminar'size='small'onClick={handleRemove}sx={{position: 'absolute',top: -10,right: -10,backgroundColor: 'white','&:hover': { backgroundColor: 'lightgray' }}}><DeleteIcon fontSize='inherit' /></IconButton></Box>)}{watchedImage instanceof File && !previewImage && (<Typography variant='caption' color='text.secondary'>Archivo seleccionado: {watchedImage.name}</Typography>)}</Box>{errors[name] && (<Typography variant='caption' color='error'>{errors[name]?.message}</Typography>)}</Box>);}