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 inputRe
f 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