I am using a mui textfield
to submit data to the database. I want to make the textfield
focus when the component is mounted using useRef
. However, I kept receiving the error: Uncaught TypeError: Cannot read properties of undefined (reading 'focus')
.
My code:
const StyledTooltip = styled(Tooltip)(({ theme }) => ({
...
}));
const CreateBox = styled(Box)(({ theme }) => ({
...
}));
const LoginTextField = styled(TextField)({
...
});
function Create () {
const inputRef = useRef();
const [openCreate, setOpenCreate] = useState(false);
const toggleCreateWindow = () => {
setOpenCreate(!openCreate);
};
useEffect(() => {
inputRef.current.focus();
}, [])
return (
<>
<Modal aria-labelledby='create' aria-describedby='create' open={openCreate} onClose={toggleCreateWindow}
closeAfterTransition BackdropComponent={Backdrop} BackdropProps={{ timeout: 500 }}>
<Fade in={openCreate}>
<CreateBox>
<LoginTextField label='Content' variant='outlined' placeholder="Writing something about Japan......" inputRef={inputRef}
multiline rows={12} maxRows={14} InputLabelProps={{ style: { color: 'white' } }} inputProps={{ style: { color: "white" } }} />
</CreateBox>
</Fade>
</Modal>
<StyledTooltip title='Create'>
<Fab aria-label='create' onClick={toggleCreateWindow}>
<EditIcon />
</Fab>
</StyledTooltip>
</>
);
};
export default Create;
Is it an unique issue for MUI textfield
? Because it works fine with the html textfield
Anybody has an idea what's wrong with my code? Much appreciated!