React open select file dialog using ref not working?

Viewed 2321

I'm trying to open file dialog using react useRef hook.

when browser executes fileInputRef.current.click() code snippet I'm getting below error in console

error: File chooser dialog can only be shown with a user activation

1 Answers

This works well:

const inputFileRef = useRef();
...
const handleBtnClick = () => {
   inputFileRef.current.click();
}
...
<form>
  <input type="file" ref={inputFileRef} />
  <button onClick={handleBtnClick}>Select file</button>
</form>
Related