How to autofocus select input after async call?

Viewed 488

I'm using Material UI's Autocomplete component, and I'm running into an issue. I have a debounced API call that is made when a user starts typing, and I disable the text input field while the call is being executed.

The issue is that disabling and then enabling the text field makes the text input lose focus. I've tried giving it an ID and grabbing it in the DOM and running .onFocus(), but that a) didn't work and b) isn't very React-y.

I also tried to add a useRef hook, but that didn't work either.

Any thoughts/suggestions?

Codesandbox

1 Answers

Hey you can add inputRef prop and then just wait until it is done loading. Here is exmaple:

const inputComponent = React.useRef(null);

return (
    <Autocomplete
      {/* ... */}
      renderInput={params => (
        <TextField
          {/* ... */}
          InputProps={{
            {/* ... */}
            inputRef: inputComponent,
            {/* ... */}
          }}
        />
      )}
    />
  );

And then I am guessing that you tried to focus element while it was still disabled, I guess a little race condition. You can add useEffect that is dependent on open and loading like this:

React.useEffect(() => {
    if (!loading && open) {
      inputComponent.current?.focus();
    }
}, [loading, open]);

Here is the link to sandbox with it. Cheers, hope it helps.

P.S I don't think it is a good idea to disable the field while options are loading, it won't feel smooth for the user :)

Related