I use Material-UI TextField
I want to implement an autofocus, I can't find a way to do it from markup by setting autofocus=true
not programmatically. any help?
I use Material-UI TextField
I want to implement an autofocus, I can't find a way to do it from markup by setting autofocus=true
not programmatically. any help?
You can do this like this: <TextField autoFocus></TextField>
.
More on this: https://facebook.github.io/react/docs/tags-and-attributes.html#html-attributes.
For some reason this was not working for me (maybe because it's within a component that's not visible when the top-level component mounts). I had to do something more convoluted to get it to work:
const focusUsernameInputField = input => {
if (input) {
setTimeout(() => {input.focus()}, 100);
}
};
return (
<TextField
hintText="Username"
floatingLabelText="Username"
ref={focusUsernameInputField}
/>
)
For more info see https://github.com/callemall/material-ui/issues/1594.
You can create a reusable hook for autofocus purposes.
export function useFocusableInput(shouldFocus: boolean) {
const inputRef = useRef<HTMLInputElement | null>(null);
const setInputRef = (instance: HTMLInputElement | null) => {
inputRef.current = instance;
};
useEffect(() => {
let timeout: NodeJS.Timeout;
if (shouldFocus) {
timeout = setTimeout(() => {
inputRef.current?.focus();
});
}
return () => {
if (timeout) {
clearTimeout(timeout);
}
};
}, [shouldFocus]);
return {
setInputRef,
};
}
Then use it for a desired textfield
const { setInputRef } = useFocusableInput(shouldFocus);
return (
...
<TextField
inputRef={setInputRef}
...
/>
)
I just simply put the ref of input into state
<TextInput inputRef={el => { this.setState({form: el}) }}/>
then you can set focus to the input anywhere.
this.state.form.focus()