unknown_boundaries
unknown_boundaries

Reputation: 1590

cancel event on input type="file" hidden

I've read Cancel event on input type="file", but this doesn't work when input tag is hidden, the focus doesn't go to input tag.

I'm looking to re-render the button when OS file-picker closes - a. either after selecting any file, b. without selecting file and clicking on cancel button

Attaching useState/useForceUpdate/useReducer on Button.onClick or input.onChange|onClick event works when user actually selects file, but "not" when user clicks on cancel button without selecting file (or when user clicks on Esc key using keyboard).

input.onFocus doesn't get trigger. Is there a way to re-render button when user is done with file-picker closes without file selection (cancel/Esc key)?

const [, forceUpdate] = React.useReducer((x) => x + 1, 0);

return (
    <>
        <input
            type="file"
            ref={uploadRef}
            id={`${toolbarButtonId}`}
            accept={acceptParams}
            onChange={onClickEvent}
            onClick={onClick}
            hidden
            onFocus={forceUpdate}
        />
        <Button
            ariaLabel={ariaLabel}
            ariaDescription={ariaDescription}
            disabled={disabled}
            iconName={iconName}
            id={toolbarButtonId}
            position={position}
            onClick={fileUploadRefLink}
            {...props}
        />
    </>
);

Upvotes: 4

Views: 721

Answers (1)

mwryl
mwryl

Reputation: 672

You could add a focus event on the window to watch when it get focused back after the user closes the file input dialog.

let button = document.querySelector("button");
let input = document.querySelector("input");

let renderCount = 0;
    
let pageRefocused =  () => {
  button.textContent = `User closed the dialog ${++renderCount} times`;
  window.removeEventListener("focus", pageRefocused);
};

button.addEventListener("click", () => {
  input.click();
  // we watch the window after opening the file input dialog
  window.addEventListener("focus",pageRefocused); 
});
input {
  visibility:hidden;
}
<button>Upload a file</button><input type="file">

Upvotes: 3

Related Questions