Differentiate between fileRejections and isDragReject in useDropzone hook

Viewed 127

I'm using fileRejections for catching files which have size larger than 5MB and isDragReject for files which are not csv like this:-

const maxSize=5242880;
const CSVDropzone = () => {
  const classes = useStyles();


  const { getRootProps, getInputProps, fileRejections, isDragActive, isDragAccept, isDragReject } = useDropzone({
    onDrop,
    accept: 'text/csv',
    minSize: 0,
    maxSize,
  });
  let isFileTooLarge = fileRejections.length > 0 && fileRejections[0].errors.length;

  return (
    <Fragment>
      <Grid container {...getRootProps()} className={classes.dropzone}>
        <input {...getInputProps()} />
        {isDragActive ? (
          <p>Drop here ...</p>
        ) : (
          <Fragment>
            <BackupOutlinedIcon />
            <p>Drag and drop or click to browse</p>
          </Fragment>
        )}
      </Grid>
      <Grid container>      
        <Grid item xs={12}>
            {isFileTooLarge && (
            <Typography variant="caption">File is too large. Allowed maximum sixe is 5 Mb.</Typography>
            )}
            {isDragReject && (
            <Typography variant="caption">Incorrect file format. Please upload a CSV file. </Typography>
            )}
        </Grid>
      </Grid>
    </Fragment>
  );
};

PROBLEM: when a non-csv file is dragged..Till the time that drag is happening, we'll see Incorrect file formatThe moment the file is dropped, we see File is too large
I feel that since isDragReject is internal to useDropzone, it is only true till the drop is in progress. I want it to stay true until the next onDrop.
Can someone suggest something?

1 Answers

I think, a state variable can help you here.

I want it to stay true until the next onDrop. Can someone suggest something?

To achieve this, we will update its value only when isDragActive is true.

For example, you can declare a state variable like,

const [isRejected, setIsRejected] = useState(false);

and before the return statement, the following condition can be added,

if (isDragActive && isRejected != isDragReject) {
    setIsRejected(isDragReject);
}

After this, you can use isRejected instead of isDragReject for your rendering.

PS: I'm still a beginner in React, so please correct me if I am making any wrong assumptions here.

Related