To focus a React Material UI TextField on button click, we assign a ref to the TextField
by assign a ref to the inputRef
orop of the TextField
.
Then we can call focus
on the element we get from the ref.
For instance, we write
import React, { useState, useRef } from "react";
const Comp = (props) => {
const textInput = useRef(null);
return (
<div>
<Button
onClick={() => {
setTimeout(() => {
textInput.current.focus();
}, 100);
}}
>
Focus TextField
</Button>
<TextField
fullWidth
required
inputRef={textInput}
name="firstName"
type="text"
placeholder="Enter Your First Name"
label="First Name"
/>
</div>
);
};
to call the useRef
to create the textInput
ref.
Then we assign textInput
as the value of the inputRef
prop.
And then we call textInput.current.focus(
to focus the element in the button’s click handler.
2 replies on “How to focus a React Material UI TextField on button click?”
Honestly, you’re a hero. Thank you for this!
Thanks for reading.