Pārlūkot izejas kodu

styled image uploader

viktoriia.kapran 1 gadu atpakaļ
vecāks
revīzija
5d06ea4364
1 mainītis faili ar 53 papildinājumiem un 12 dzēšanām
  1. 53 12
      js21 react/my-react-app/src/components/ImageUploader.js

+ 53 - 12
js21 react/my-react-app/src/components/ImageUploader.js

@@ -1,10 +1,53 @@
-import React from 'react';
+import React, {useCallback, useMemo} from 'react';
 import { useUploadImageMutation } from '../store/api';
-import Dropzone from 'react-dropzone'
+import {useDropzone} from 'react-dropzone';
+
+const baseStyle = {
+  flex: 1,
+  display: 'flex',
+  flexDirection: 'column',
+  alignItems: 'center',
+  padding: '20px',
+  borderWidth: 2,
+  borderRadius: 2,
+  borderColor: '#eeeeee',
+  borderStyle: 'dashed',
+  backgroundColor: '#fafafa',
+  color: '#bdbdbd',
+  outline: 'none',
+  transition: 'border .24s ease-in-out'
+};
+
+const focusedStyle = {
+  borderColor: '#2196f3'
+};
+
+const acceptStyle = {
+  borderColor: '#00e676'
+};
+
+const rejectStyle = {
+  borderColor: '#ff1744'
+};
 
 function ImageUploader() {
   const [uploadImage, result] = useUploadImageMutation();
 
+  const onDrop = useCallback(acceptedFiles => {
+    fileUpload(acceptedFiles[0]);
+  }, [])
+  const {getRootProps, getInputProps, isDragActive, isFocused, isDragAccept, isDragReject} = useDropzone({accept: {'image/*': []}, onDrop});
+
+  const style = useMemo(() => ({
+    ...baseStyle,
+    ...(isFocused ? focusedStyle : {}),
+    ...(isDragAccept ? acceptStyle : {}),
+    ...(isDragReject ? rejectStyle : {})
+  }), [
+    isFocused,
+    isDragAccept,
+    isDragReject
+  ]);
 
   function fileUpload(file) {
     const formData = new FormData()
@@ -15,16 +58,14 @@ function ImageUploader() {
   }
 
   return (
-    <Dropzone onDrop={acceptedFiles => fileUpload(acceptedFiles[0])}>
-      {({ getRootProps, getInputProps }) => (
-        <section>
-          <div {...getRootProps()}>
-            <input {...getInputProps()} />
-            <p>Drag 'n' drop some files here, or click to select files</p>
-          </div>
-        </section>
-      )}
-    </Dropzone>
+    <div {...getRootProps({style})}>
+      <input {...getInputProps()} />
+      {
+        isDragActive ?
+          <p>Drop the files here ...</p> :
+          <p>Drag 'n' drop some files here, or click to select files</p>
+      }
+    </div>
   )
 }