[HOWTO] Focus Material UI v4 TextField on button click

In a project I’m currently working I had to set the focus to a Material UI (MUI) version 4 TextField as soon as a button gets clicked. As another input field should be focused after page is loaded, autoFocus did not do the trick. Furthermore the MUI TextField is rendered conditionally.

After some research and with information out of the official ReactJS documentation I ended up with the following solution.

function MyComponent(props) {
  const [ addButtonClicked, setAddButtonClicked ] = useState<boolean>(false);
  const [ isAddFormVisible, setIsAddFormVisible ] = useState<boolean>(props.isAddFormVisible);
  
  // textFieldInput must be declared here so the innerRef can refer to it
  const textFieldInput = useRef<HTMLInputElement>(null);
  
  useEffect(() => {
    if (addButtonClicked) {
      textFieldInput.current?.focus();
    }
  }, [ addButtonClicked ]);

  return (
    <div>
	  { !isAddFormVisible && (
	    <IconButton
	      onClick={() => {
            setIsAddFormVisible(true);
            setAddButtonClicked(true);
          }}
        >
          <PersonAdd />
	    </IconButton>
	  )}
	  { isAddFormVisible && (
        <TextField
          id="myTextField"
		  name="myTextField"
		  inputRef={textFieldInput}
		  label="myLabel"
		  type="text"
		  fullWidth
          value={props.value}
		  disabled={props.readOnly}
		/>
      )}
    </div>
  );
}

ReactJS version: 17.0.2

Important: Material UI TextField is a component that consists of a label and an input component/element. Therefore I have to use inputRef instead of ref to make it work. Furthermore focus function has to be called in useEffect hook; otherwise textInputField will be null as TextField is not yet rendered.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Website Powered by WordPress.com.

Up ↑

%d bloggers like this: