Search code examples
reactjsreact-dropzone

How to open react-dropzone input file dialog programatically?


I am using noClick and would like to have a button open the file dialog.


Solution

  • Found how in the docs.

    You can programmatically invoke the default OS file prompt; just use the open method returned by the hook.

    import React from 'react';
    import {useDropzone} from 'react-dropzone';
    
    function Dropzone(props) {
      const {getRootProps, getInputProps, open, acceptedFiles} = useDropzone({
        // Disable click and keydown behavior
        noClick: true,
        noKeyboard: true
      });
    
      const files = acceptedFiles.map(file => (
        <li key={file.path}>
          {file.path} - {file.size} bytes
        </li>
      ));
    
      return (
        <div className="container">
          <div {...getRootProps({className: 'dropzone'})}>
            <input {...getInputProps()} />
            <p>Drag 'n' drop some files here</p>
            <button type="button" onClick={open}>
              Open File Dialog
            </button>
          </div>
          <aside>
            <h4>Files</h4>
            <ul>{files}</ul>
          </aside>
        </div>
      );
    }
    
    <Dropzone />