setFocus() in searchbar ionic4

I’m working in ionic4 REACT JS and after a search occurs I want to set focus back in the search bar, at the end. What’s the strategy to do this in React? I see the docs mention a “signature” of setFocus() => Promise but am not sure what that means and there’s no sample code for react that I could find.

Note: in general I’m not sure how to call the Methods I see listed in the ionic docs within React. plain JS looks like jquery select an element then add an event listener. But presuming there’s a more elegant React way. Any help appreciated.

Thanks

1 Like

I’d like some assistance with setting focus on the input element of the searchbar component in React as well!

Hey,

I managed to set focus by using ref in react.


async function focusElement(ref) {
  if (ref) {
    const el = await ref.getInputElement();
    el.focus();
  } else {
    console.log("focusElement got no ref");
  }
}

// Component:

function SomeComponent() {
const someRef = React.useRef()

return (
<button onClick={ () => {
    focusElement(someRef.current)
  }
>
   focus
</button>
<IonInput ref={someRef} />
)

}

      


I tried using setFocus() in a similar way but wasnt succesfull.

Would be nice to get some official examples or better docs for the intended way to set focus in Ionic React