FilesDragAndDrop

mail@pastecode.io avatar
unknown
jsx
2 years ago
2.3 kB
2
Indexable
Never
import React, { useCallback, useEffect, useState } from "react";
import Image from "next/image";
import { useDropzone } from "react-dropzone";
import { useField, useFormikContext } from "formik";
import SingleFileUploadCard from "../ui/single-file-upload";

export default function FilesDragAndDrop({ name }) {
  const [, , helpers] = useField(name);
  const [files, setFiles] = useState([]);

  const onDrop = useCallback((accFiles) => {
    // Do something with the file
    const mappedAcc = accFiles.map((file) => ({ file, errors: [] }));
    setFiles((curr) => [...curr, ...mappedAcc]);
  }, []);

  useEffect(() => {
    helpers.setValue(files);
  }, [files]);

  const { getRootProps, getInputProps, isDragActive, isDragReject } =
    useDropzone({
      onDrop,
      accept: "image/*,.pdf",
      maxSize: 10485760,
    });

  return (
    <div
      {...getRootProps()}
      className={`flex flex-col items-center justify-center h-full border-2 hover:border-primary transition duration-150 border-gray-400 border-dashed rounded-lg cursor-pointer ${
        isDragActive ? "border-primary" : "border-gray-400"
      } `}
    >
      <input {...getInputProps()} />
      <div className="space-y-3 text-center">
        <div className="relative mx-auto w-9 h-9">
          <Image src="/images/path.svg" layout="fill" objectFit="contain" />
        </div>
        <div>
          <p className="space-y-1 text-sm">
            <span className="text-primary">Upload a file</span> or drag and drop
          </p>
          <p className="text-xs text-gray-400">PNG, JPG, PDF up to 10MB</p>
        </div>
      </div>
      {/* {JSON.stringify(files)} */}
      {isDragReject && <p>File is not supported</p>}
      {files.map((fileWrapper, idx) => (
        <SingleFileUploadCard key={idx} file={fileWrapper.file} />
      ))}
    </div>
  );
}

{
  /* <div className="space-y-3 text-center">
<div className="relative mx-auto w-9 h-9">
  <Image src="/images/path.svg" layout="fill" objectFit="contain" />
</div>
<div>
  <p className="space-y-1 text-sm">
    <span className="text-primary">Upload a file</span> or drag and drop
  </p>
  <p className="text-xs text-gray-400">PNG, JPG, PDF up to 10MB</p>
</div>
</div> */
}