How to set focus to a materialUI TextField?

Material Ui

Material Ui Problem Overview


How can I set the focus on a material-ui TextField component?

componentDidMount() {
    ReactDom.findDomNode(this.refs.myControl).focus()
}

I have tried above code, but it does not work :(

Material Ui Solutions


Solution 1 - Material Ui

You can use the autoFocus attribute.

<TextField value="some value" autoFocus />

Solution 2 - Material Ui

For React 16.8.6, you should use the inputRef property of TextField to set focus. I tried ref property but it doesn't work.

<TextField
  inputRef={input => input && input.focus()}
/>

Material-ui doc says: > inputRef: Use this property to pass a ref callback to the native input component.

Solution 3 - Material Ui

autoFocus was also not working for me, perhaps since this is a component that's not mounted when the top-level component loads. I had to do something a lot more convoluted to get it to work:

function AutoFocusTextField(props) {
  const inputRef = React.useRef();

  React.useEffect(() => {
    const timeout = setTimeout(() => {
      inputRef.current.focus();
    }, 100);

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

  return <TextField inputRef={inputRef} {...props} />;
}

Note that for some reason it does not work without the setTimeout. For more info see https://github.com/callemall/material-ui/issues/1594.

Solution 4 - Material Ui

If you are using material-ui TextField and react functional component, you can pass inputRef in your TextField component. The trick here is the if condition if(input != null).

<TextField
    variant="filled"
    inputRef={(input) => {
      if(input != null) {
         input.focus();
      }
    }}
/>

Here is an working example for you. CodeSandBox- Material-ui-TextFieldFocus

Solution 5 - Material Ui

This will focus the component every time it renders. Other solutions I tried only focus the element an initial time.

  const inputRef = React.useRef<HTMLInputElement>();
  
  useEffect(() => {
    inputRef.current?.focus();
  }, [inputRef.current]);

  const setTextInputRef = (element: HTMLInputElement) => {
    inputRef.current = element;
  };
   
  return (
    <TextField
      inputRef={setTextInputRef}
    />

Solution 6 - Material Ui

 const handleClick =  () => {
   inputRef.current.firstChild.focus();
   inputRef.current.firstChild.placeholder = '';
  }
  <InputBase
        value={value}
        ref={inputRef}
        placeholder="search" />
    <Button onClick={handleClick}>Click</Button>

Solution 7 - Material Ui

This code is actually good, but has a drawback, on every render it's going to create a new function. It easily can be solved using useCallback

<TextField
  inputRef={input => input && input.focus()}
/>

Should be

const callbackRef = useCallback((inputElement) => {
     if (inputElement) {
         inputElement.focus();
     }
 }, []);
...
<TextField
  inputRef={callbackRef}
/>

Solution 8 - Material Ui

add this propery to your TextField component :

inputRef={(input) => input?.focus()}

Solution 9 - Material Ui

I am using this solution, works for text fields inspired by https://gist.github.com/carpben/de968e377cbac0ffbdefe1ab56237573


const useFocus = (): [any, () => void] => {
    const htmlElRef: MutableRefObject<any> = useRef<HTMLDivElement>();
    const setFocus = (): void => {
        if (!htmlElRef || !htmlElRef.current) return
        const div = htmlElRef.current as HTMLDivElement
        if (!div) return
        const input = div.querySelector("input")
        if (input) input.focus()
    }
    return [htmlElRef, setFocus];
};


export function MyComp() {
  const [ref, setFocus] = useFocus()
  
  // use setFocus() to focus the input field

  return <Input ref={ref} />
}

Solution 10 - Material Ui

For a material ui TextField you need to input the props for autoFocus in a inputProps object like this.

 <TextField inputProps={{ autoFocus: true }} />

Solution 11 - Material Ui

AlienKevin is correct ( pass a ref callback to "TextField.inputProps" ), but you can also save the element reference on your "this" object, so that you can set focus later. Here is an example in Coffeescript:

TextField
	inputProps:
		ref: (el)=>
			if el?
				@input_element = el

Button
	onClick:=> 
		@input_element.focus()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGiles BradshawView Question on Stackoverflow
Solution 1 - Material UiAntonis ZisisView Answer on Stackoverflow
Solution 2 - Material UiAlienKevinView Answer on Stackoverflow
Solution 3 - Material UiLane RettigView Answer on Stackoverflow
Solution 4 - Material UiatbrakhiView Answer on Stackoverflow
Solution 5 - Material Uia2f0View Answer on Stackoverflow
Solution 6 - Material UiMohammed Azhar UddinView Answer on Stackoverflow
Solution 7 - Material UiPetr SchukinView Answer on Stackoverflow
Solution 8 - Material Uiuser345View Answer on Stackoverflow
Solution 9 - Material UilcapraView Answer on Stackoverflow
Solution 10 - Material UiStalliView Answer on Stackoverflow
Solution 11 - Material UiNick PerkinsView Answer on Stackoverflow