Jaaneek / useFilePicker

Simple react hook to open browser file selector.

Home Page:https://use-file-picker.vercel.app

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

If you don't append the input element on body on iOS it doesn't work

alessandro-bottamedi opened this issue · comments

change and blur event will not fire on iOS without append input element to the body.

I suggest these changes to the openFileDialog file:

/helpers/openFileDialog.ts:

export function openFileDialog(accept: string, multiple: boolean, callback: (arg: Event) => void) {
  // this function must be called from a user
  // activation event (ie an onclick event)

  // Create an input element
  var inputElement = document.createElement('input');
  // Hide element and append to body (required to run on iOS safari)
  inputElement.style.display = 'none';
  document.body.appendChild(inputElement);
  // Set its type to file
  inputElement.type = 'file';
  // Set accept to the file types you want the user to select.
  // Include both the file extension and the mime type
  inputElement.accept = accept;
  // Accept multiple files
  inputElement.multiple = multiple;
  // set onchange event to call callback when user has selected file
  //inputElement.addEventListener('change', callback);
  inputElement.addEventListener('change', arg => {
    callback(arg);
    // remove element
    document.body.removeChild(inputElement);
  });
  // set onblur event to call callback when user has selected file on Safari
  inputElement.addEventListener('blur', arg => {
    callback(arg);
    // remove element
    document.body.removeChild(inputElement);
  });
  // dispatch a click event to open the file dialog
  inputElement.dispatchEvent(new MouseEvent('click'));
}

With this implementation everything works fine.

Looks good
What do you think @MrKampla @GitKokoszka

We tried to avoid appending anything to the actual DOM, but in this case there are no other options left, as adding only blur event handler didn't help on iOS. So I think this code suggestion is fine. @alessandro-bottamedi You're welcome to create a PR with this change. If not, then we'll take care of it.

Here the PR: #35

I'm closing the issue as Your changes in the PR #35 were merged and released with version 1.4.2. Thank You for Your input.