ReactJS- Directory selection dialog not working

Viewed 1529

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;
  }
}

1 Answers

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} />;
}
Related