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
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.
You can try and use React’s
useRef
anduseEffect
hooks:The
useRef
hook creates a reference (inputRef
) to theIonInput
element.The
useEffect
hook makes sure the focus is set on theIonInput
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 useref={inputRef}
instead of theautofocus
attribute.That does set the focus on the
IonInput
field for ‘First Name’ whenMyForm
component is rendered.You can see it in action in this stackblitz.