drag and drop

parent 1beb2338
......@@ -110,7 +110,12 @@ const ProductForm = () => {
</Grid2>
<Grid2>
<FileInput name='image' label='Image' onChange={onFileChange} />
<FileInput
name='image'
label='Image'
onChange={onFileChange}
accept={'image/*'}
/>
</Grid2>
<Grid2>
......
'use client'
import { Button, Grid2, styled, TextField } from '@mui/material'
import { Box, Button, Grid2, styled, TextField } from '@mui/material'
import { ChangeEvent, useRef, useState } from 'react'
interface IProps {
name: string
label: string
onChange: (e: ChangeEvent<HTMLInputElement>) => void
accept?: string
}
const HiddenFileInput = styled('input')({ display: 'none' })
const FileInput = ({ name, label, onChange }: IProps) => {
const dragZoneStyles = {
border: '2px dashed #a7a7a7',
borderRadius: '8px',
cursor: 'pointer',
}
const FileInput = ({ name, label, onChange, accept }: IProps) => {
const inputRef = useRef<HTMLInputElement>(null)
const [fileName, setFileName] = useState('')
const [isDragging, setIsDragging] = useState(false)
const activeInput = () => {
const openDialog = () => {
if (inputRef?.current) {
inputRef.current.click()
}
......@@ -23,14 +31,37 @@ const FileInput = ({ name, label, onChange }: IProps) => {
const onFileChange = (e: ChangeEvent<HTMLInputElement>) => {
const file = e.target.files[0].name
console.log(e.target.files)
if (file) {
setFileName(file)
onChange(e)
}
}
const prevent = (e: DragEvent) => {
e.preventDefault()
e.stopPropagation()
}
const onDragOver = (e: any) => {
prevent(e)
if (!isDragging) setIsDragging(true)
}
const onDragLeave = (e: any) => {
prevent(e)
setIsDragging(false)
}
const onDrop = (e: any) => {
prevent(e)
setIsDragging(false)
const file = e.dataTransfer?.files?.[0]
if (!file) return
setFileName(file.name)
}
return (
<>
<HiddenFileInput
......@@ -38,22 +69,35 @@ const FileInput = ({ name, label, onChange }: IProps) => {
name={name}
onChange={onFileChange}
ref={inputRef}
accept={accept}
/>
<Grid2 container direction='row' spacing={2} alignItems={'center'}>
<Grid2>
<TextField
variant='outlined'
fullWidth
label={label}
value={fileName}
disabled
onClick={activeInput}
/>
<Box
sx={{
...dragZoneStyles,
background: isDragging ? 'gray' : 'transparent',
borderColor: isDragging ? 'gray' : 'transparent',
}}
role='button'
onDragOver={onDragOver}
onDragLeave={onDragLeave}
onDrop={onDrop}
>
<TextField
variant='outlined'
fullWidth
label={label}
value={fileName}
disabled
placeholder='Перетащите файл сюда или нажмите на выбор'
/>
</Box>
</Grid2>
<Grid2>
<Button variant='contained' onClick={activeInput}>
<Button variant='contained' onClick={openDialog}>
Browse
</Button>
</Grid2>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment