18

I use Material-UI TextField

I want to implement an autofocus, I can't find a way to do it from markup by setting autofocus=true not programmatically. any help?

Amr M. AbdulRahman
  • 1,820
  • 3
  • 14
  • 22
  • 2
    Possible duplicate of [How to set focus to a materialUI TextField?](https://stackoverflow.com/questions/37949394/how-to-set-focus-to-a-materialui-textfield) – Lane Rettig Jun 16 '17 at 11:03

4 Answers4

37

You can do this like this: <TextField autoFocus></TextField>.

More on this: https://facebook.github.io/react/docs/tags-and-attributes.html#html-attributes.

Richard
  • 14,427
  • 9
  • 57
  • 85
Deividas
  • 6,437
  • 2
  • 26
  • 27
8

For some reason this was not working for me (maybe because it's within a component that's not visible when the top-level component mounts). I had to do something more convoluted to get it to work:

const focusUsernameInputField = input => {
  if (input) {
    setTimeout(() => {input.focus()}, 100);
  }
};

return (
  <TextField
    hintText="Username"
    floatingLabelText="Username"
    ref={focusUsernameInputField}
  />
)

For more info see https://github.com/callemall/material-ui/issues/1594.

Lane Rettig
  • 6,640
  • 5
  • 42
  • 51
  • 1
    "...The element must be visible in order to be focusable. Elements of the following type are focusable if they are not disabled: input, select, textarea, button, and object. Anchors are focusable if they have an href or tabindex attribute. area elements are focusable if they are inside a named map, have an href attribute, and there is a visible image using the map. All other elements are focusable based solely on their tabindex attribute and visibility.": From https://api.jqueryui.com/focusable-selector/ – jobmo Oct 06 '17 at 09:15
  • Works with inputRef={focusUsernameInputField} – Bogy Dec 16 '22 at 09:06
2

You can create a reusable hook for autofocus purposes.

  export function useFocusableInput(shouldFocus: boolean) {
    const inputRef = useRef<HTMLInputElement | null>(null);
    const setInputRef = (instance: HTMLInputElement | null) => {
      inputRef.current = instance;
    };

    useEffect(() => {
      let timeout: NodeJS.Timeout;
      if (shouldFocus) {
        timeout = setTimeout(() => {
          inputRef.current?.focus();
        });
      }

      return () => {
        if (timeout) {
          clearTimeout(timeout);
        }
      };
    }, [shouldFocus]);

    return {
      setInputRef,
    };
  }

Then use it for a desired textfield

const { setInputRef } = useFocusableInput(shouldFocus);
return (
...
<TextField
  inputRef={setInputRef}
  ...
/>
)
1

I just simply put the ref of input into state

<TextInput inputRef={el => { this.setState({form: el}) }}/>

then you can set focus to the input anywhere.

this.state.form.focus()