why is useRef not working with Material UI TextField but works fine with a traditional html input element?
The UI:
I have a Textfield input element and above it I have a list of buttons (letters from the latin alphabet, special characters). I can focus the input bar when the component renders the first time, but if I click on one of the buttons above the input, the focus is not back on the input bar.
What I tried so far
const Search = (props) => {
const [searchTerm, setSearchTerm] = useState("");
const inputRef = useRef(null);
const handleLatinButton = (letter) => {
inputRef.current.focus();
setSearchTerm(searchTerm + letter);
};
const handleSubmit = (e) => {
e.preventDefault();
History.push("/?q=" + searchTerm);
props.onFormSubmit(searchTerm, optionValue);
setSearchTerm("");
};
useEffect(() => {
const params = new URLSearchParams(location.search);
const q = params.get("q");
setSearchTerm(q);
inputRef.current.focus();
}, []); // Am I missing something here in the array?
JSX
<Button letter="č" handleLatinButton={handleLatinButton} />
<Button letter="ḍ" handleLatinButton={handleLatinButton} />
...
<form onSubmit={handleSubmit}>
<TextField
fullWidth
label="Search..."
value={searchTerm}
onChange={handleChange}
ref={inputRef}
autoFocus="true"
InputProps={{
endAdornment: (
<InputAdornment position="start">
<IconButton type="submit">
<SearchIcon />
</IconButton>
</InputAdornment>
),
}}
/>
</form>
If I replace TextField with input, the focus works after I click on one of the latin buttons.