Unable to trigger input event from label element with keyboard

154 Views Asked by At

When I click the label with the mouse I get the file browser popup as expected. But when I use the keyboard and tab to the label and hit enter I don't.

<>
  <label className="button" htmlFor="fileUploadInput" tabIndex={0}>
    Upload File
  </label>
  <input id="fileUploadInput" type="file" onChange={handleChange} />
</>

To create a custom file input button, the label has all the fancy styling and is visible. The input has the style below.

input {
  visibility: hidden;
  height: 0;
  width: 0;
}
1

There are 1 best solutions below

0
RubenSmn On BEST ANSWER

As mentioned in the comments there is no native way to handle this. I ended up creating a ref for the input. And added a onKeyUp event on the label which allowed to programmaticly open the file browser dialog when the enter key was clicked.

const inputRef = useRef(null);

const handleLabel = (e) => {
  if (e.key !== "Enter" || inputRef.current === null) return;
  inputRef.current.click();
};

<>
  <label
    className="button"
    htmlFor="fileUploadInput"
    tabIndex={0}
    onKeyUp={handleLabel}
  >
    Upload File
  </label>
  <input
    ref={inputRef}
    id="fileUploadInput"
    type="file"
    onChange={handleChange}
  />
</>