2

I have TextField inside Dialog, which I want to focus everytime Dialog is opened. I tried using inputRef callback, but TextField doesn't get focused. Adding autoFocus prop to TextField also doesn't help.

Minimal example:

import { Button, Dialog, DialogContent, TextField } from "@mui/material";
import { useState } from "react";

function ExampleDialog(props: { isOpen: boolean; onClose: () => void }) {
  return (
    <Dialog open={props.isOpen} onClose={props.onClose}>
      <DialogContent>
        <TextField inputRef={(input) => input && input.focus()} fullWidth />
      </DialogContent>
    </Dialog>
  );
}

function App() {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <div>
      <Button
        variant="contained"
        color="success"
        onClick={() => {
          setIsOpen(true);
        }}
      >
        Open dialog
      </Button>

      <ExampleDialog isOpen={isOpen} onClose={() => setIsOpen(false)} />
    </div>
  );
}
  • react version: 18.2.0
  • @mui/material version: 5.11.16

1 Answer 1

12

Did you check this https://github.com/mui/material-ui/issues/33004

Seems like the Strict mode in React 18 breaks that behaviour

Either remove it or add disableRestoreFocus prop to the Dialog component

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.