Rev 3452 | AutorÃa | Ultima modificación | Ver Log |
import React, { useState } from 'react';
import { useFormContext } from 'react-hook-form';
import { Button, IconButton, Box, Typography, FormControl, InputLabel } 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, styles, ...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 (
<FormControl variant='standard' fullWidth sx={styles}>
{label && <InputLabel shrink>{label}</InputLabel>}
<Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
<Button component='label' variant='outlined' startIcon={<PhotoCamera />}>
Subir Imagen
<VisuallyHiddenInput
id={name}
name={name}
type='file'
onChange={handleChange}
{...register(name)}
{...rest}
/>
</Button>
{previewImage && (
<Box sx={{ position: 'relative' }}>
<img
src={previewImage}
alt='Vista previa'
style={{ height: 100, width: 100, objectFit: 'cover' }}
/>
<IconButton
aria-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>
)}
</FormControl>
);
}