0
votes

In my class component I have a ref object to select files from a selected folder. So, I add attributes directory and webkitdirectory in componentDidMount as

export class ImportForm extends React.Component<ImportFormProps,ImportFormState> {
  constructor(props:ImportFormProps){
    super(props);
    this.state={
      folderInput: React.createRef()
    }
  }
  componentDidMount(){
    if (this.state.folderInput.current !== null) {
      this.state.folderInput.current.setAttribute("directory", "");
      this.state.folderInput.current.setAttribute("webkitdirectory", "");
    }
  }
.
.
.

I'm changing the above class component to FunctionComponent. Now, I'm using useRef react hook to use folder reference. But adding attributes directory and webkitdirectory is not adding these attributes to my folder selection input. That is, my input element is not working as it was working in class component. Here is my code

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

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

Is useEffect hook right place to add these attributes?

What I'm doing wrong?

I tried this solution but not working.

Thanks!

1

1 Answers

-1
votes

I did not see your error message but I can write usage of useRef

const inputRef = useRef();

useEffect(() => {
  folderInput.current.setAttribute('directory', '');
 folderInput.current.setAttribute('webkitdirectory', '');
}, [folderInput]);


  return <Input ref={inputRef} /> ;