4

I want a directory selection dialog in my React App. I followed this SO thread that might work for some people but not for me. Getting compile time error as

Property 'directory' does not exist on type 'DetailedHTMLProps<InputHTMLAttributes, HTMLInputElement>'.

enter image description here

I upgraded react to the latest RC-version 17.rc.1 thinking that there may be a bug fix for this but no success.

Edit

There is a hack to add this script at the end of file using tag for directory selection, suggested by @Scratch'N'Purr in comments.

declare module 'react' {
  interface HTMLAttributes<T> extends AriaAttributes, DOMAttributes<T> {
    // extends React's HTMLAttributes
    directory?: string;
    webkitdirectory?:string;
  }
}

DevLoverUmar
  • 11,809
  • 11
  • 68
  • 98

1 Answers1

10

It works fine in Javascript but the problem is with Typescript. Guess, you are right about it being an issue.

You can set it manually using ref though.

import * as React from "react";
import "./styles.css";

export default function App() {
  const ref = React.useRef<HTMLInputElement>(null);

  React.useEffect(() => {
    if (ref.current !== null) {
      ref.current.setAttribute("directory", "");
      ref.current.setAttribute("webkitdirectory", "");
    }
  }, [ref]);

  return <input type="file" ref={ref} />;
}
sidthesloth
  • 1,399
  • 1
  • 11
  • 19
  • very rare answer for `ReactJS` with `TypeScript`, to add `directory` and `webkitdirectory` to `input` files, very good reply. – ArifMustafa Jul 26 '23 at 17:55