reactjstypescriptreact-functional-component

How to focus on dynamically added Input field in react


On button click I am showing a dialog which have input field. I want to autofocus in that input field. I'm using Material UI Component Dialog & OutlinedInput

const SearchIdDialog: React.FC = () => {
  const [openSearchId, setOpenSearchId] = React.useState<boolean>(false);

  React.useEffect(()=> {
    inputRef.current?.focus();
  }, [openSearchId]);

  const handleClose = () => {
    setOpenSearchId(false);
  };

  const inputRef = React.useRef<HTMLInputElement>(null);

  return (
    <div>
      <Tooltip title="Click to search">
        <Button
          onClick={() => {
            setOpenSearchId(true);
          }}
        >
          Search
        </Button>
      </Tooltip>

      <BootstrapDialog
        onClose={handleClose}
        open={openSearchId}
      >
        <SearchStyle
          inputRef={inputRef}
        />
      </BootstrapDialog>
    </div>
  );
};

I have tried autoFocus prop but its failing. How to wait for input field to render input field first and then focusing it ?

Note: inputRef is used instead of ref because its a mui component which need inputRef. If I use setTimeOut in useEffect and waits for 1 sec and then focus - it works. But I want it naturally.

Sandbox link- https://codesandbox.io/s/react-typescript-forked-f6hg5y?file=/src/SearchIdDialog.tsx


Solution

  • Since autofocus is not working, then you can try with setTimeout.

    What I did was to check if openSearchId is true Demo

      React.useEffect(() => {
        if (openSearchId) {
          setTimeout(() => {
            inputRef.current?.focus();
            console.log("focused");
          }, 300);
        }
      }, [openSearchId]);
    

    Does this work for you? You can change the millis of course.