skip to Main Content

I’m using Ionic 7 and React 18. How do I cause a particular input on a form to automatically have the focus of the cursor when that component is loaded? I thought "autofocus" was the way

          <IonInput
          autofocus
            placeholder='First Name'
            value=''
          />

but that is not getting the cursor focus. An example can be seen here — https://stackblitz.com/edit/an5yjh-xqjw5k?file=src%2FApp.tsx,src%2Fcomponents%2FMyForm.tsx .

Edit: Per the answer given, I tried this but the focus does not set to the only field on the page.

2

Answers


  1. There is a method Ionic provides for IonInput component called: setFocus

    The example provided will not work b/c you’re using a submit type button, using a regular IonButton works.

    const MyForm = () => {
      const firstNameInput = useRef<HTMLIonInputElement>(null);
      const handleButtonClick = () => {
        firstNameInput.current?.setFocus();
      };
    
      return (
        <>
          <form>
            <IonInput ref={firstNameInput} placeholder="First Name" value="" />
            <IonButton onClick={handleButtonClick}>Focus Input</IonButton>
            {/* <IonButton type="submit">Save And Continue</IonButton> */}
          </form>
        </>
     );
    };
    
    Login or Signup to reply.
  2. You can try and use React’s useRef and useEffect hooks:

    import React, { useEffect, useRef } from 'react'
    import { IonButton, IonInput } from '@ionic/react'
    
    const MyForm = () => {
      const inputRef = useRef<HTMLIonInputElement>(null);
    
      useEffect(() => {
        setTimeout(() => { // Added a timeout to make sure the element is loaded
          inputRef.current?.setFocus();
        }, 0);
      }, []);
    
      return (
        <form>
          <IonInput
            ref={inputRef}
            placeholder='First Name'
            value=''
          />
        
          <IonButton type='submit'>Save And Continue</IonButton>
        </form>
      );
    }
    
    export default MyForm;
    

    The useRef hook creates a reference (inputRef) to the IonInput element.
    The useEffect hook makes sure the focus is set on the IonInput when the component mounts. A timeout is used to make sure the DOM element is loaded before trying to set focus.
    The IonInput is updated to use ref={inputRef} instead of the autofocus attribute.

    That does set the focus on the IonInput field for ‘First Name’ when MyForm component is rendered.

    You can see it in action in this stackblitz.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search