IonInput for files? v5

I want to allow the users to upload images in my PWA. It seems that the IonInput is a wrapper for HTML input, but does not allow file inputs.

Combining <input /> with <label> in standard HTML does the job but looks ugly.

In the Docs i can only find file upload in the native components.

Maybe you could use the working standard html elements and apply the ionic styles with a class

<input class="ion-input>

Unfortunately that didn’t work, but it pointed me somehow into the right direction.

React allows you to store a reference to any HTML object. You can use this reference to manually trigger a click event when the beautiful IonButton is pressed while hiding the <input/>

The solution looks like this:

...
const [inputElement, setInputElement({} as HTMLInputElement);
return <IonButton onClick={() => inputElement.click()} expand="block">
          <input
            accept="image/*"
            hidden
            ref={input => (input !== null ? setInputElement(input) : null)}
            type="file"
            onChange={e =>
              setFile(
                (e.nativeEvent.target as HTMLInputElement).files?.item(0) ||
                  ({} as File)
              )
            }
          />
          <IonIcon slot="start" icon={imageOutline} />
          Choose Image
        </IonButton>

  const fileInput = useRef(null);


    <>
      <input
        ref={fileInput}
        hidden
        type="file"
        accept="image/*"
        onChange={onSelectFile}
        onClick={() => {
          console.log('onClick');
        }}
      />
      <IonButton
        color="primary"
        onClick={() => {
          // @ts-ignore
          fileInput?.current?.click();
          // setBackgroundOption(BackgroundOptionType.Gradient);
        }}>
        Image
      </IonButton>
</>
1 Like