Categories
React Answers

How to focus a React Material UI TextField on button click?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

2 replies on “How to focus a React Material UI TextField on button click?”

Leave a Reply

Your email address will not be published. Required fields are marked *