How to make Select Directory using React?
Asked Answered
F

2

8

I need to upload all files from a folder to server. I'm trying to implement Select Directory window, and not Select file.

The normal way like:

<input type="file" webkitdirectory directory/>

Did not work for me, and showed Select File window.

But when I created empty regular html file with this input tag, it was working fine. Does anybody know how to implement the solution using React?

Thank you!

Footplate answered 2/8, 2019 at 10:5 Comment(1)
Rich Warrior answer is correct just select directory and push Upload buton. codesandbox.io/embed/dreamy-bouman-kswbgMorello
P
9

try bheptinh.

<input directory="" webkitdirectory="" type="file" />
Prairial answered 2/8, 2019 at 16:43 Comment(2)
I am glad to helpPrairial
sorry I tried to extract the path from this element and I got my path something like C:\Downloads\fakepath\firstFileInsideChosenPath.txt I need the actual selected path. Can someone help me on this please?Bouchier
D
2

In React 17 with Typescript, if you are using useRef Hook, the best bet is to extend React's HTMLAttributes (in the same file of your input) and then simply add directory and webkitdirectory attributes in input tag as

import * as React from "react";

export const ImportForm: React.FunctionComponent<FormProps> = (props) => {
const folderInput= React.useRef(null);

return (
<>
           <div className="form-group row">
              <div className="col-lg-6">
                <label>Select Folder</label>
              </div>
              <div className="col-lg-6">
                <input
                  type="file"  
                  directory=""
                  webkitdirectory=""                
                  className="form-control"
                  ref={folderInput}
                />
              </div>
            </div>
</>)
};

declare module 'react' {
  interface HTMLAttributes<T> extends AriaAttributes, DOMAttributes<T> {
    // extends React's HTMLAttributes
    directory?: string;        // remember to make these attributes optional....
    webkitdirectory?: string;
  }
}
Discontent answered 17/11, 2020 at 5:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.