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.
You can try and use React's
useRef
anduseEffect
hooks:The
useRef
hook creates a reference (inputRef
) to theIonInput
element. TheuseEffect
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.
Yes, I have update the stackblitz.
Since the rendering of the
IonInput
is straightforward and not heavily dependent on asynchronous operations, the simplest and most effective approach should be to make sure the focus is set after the component and all its children are fully mounted.The
MutationObserver
will watch for changes in the DOM. When it detects changes, it checks if theIonInput
is available and sets the focus.The disconnecting observer (mentioned here) allows, once the focus is set, for the observer to be disconnected to prevent further unnecessary checks.