React Material Programmatically Set Focus on a TextField

Overview

Short post on how to programmatically set the focus on a text field. This is useful when clicking a button and putting the cursor on a field so the user can continue typing. Otherwise, once a button is clicked, the focus will remain on the button. One of many use cases is building a custom search field with an end adornment for clearing the search term and putting the cursor back so the user can type another string.

Set Focus with useRef Hook

Import the useRef hook from react.

import { useRef } from 'react';

Create a new const inputRef with the useRef hook inside a function that has the text field.

export default function YourCompoent(props) {
    const inputRef  = useRef();

When the button is clicked it will call clearSearchString to set the searchTerm state and put the focus back on the text field.

const [searchTerm, setSearchTerm] = useState('');

  const clearSearchString = (event) => {   
    setSearchTerm('');    
    inputRef.current.focus()
  }

Set the inputRef in the text field.

 <TextField inputRef={inputRef} 

All Together

Everything from above plus the missing imports.

import React, { useRef, useState } from 'react';
import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';

export default function YourCompoent(props) {
  const inputRef  = useRef();

  const [searchTerm, setSearchTerm] = useState('');

  const clearSearchString = (event) => {   
    setSearchTerm('');    
    inputRef.current.focus()
  }

return (
 <>
    <Button variant="outlined" onClick={clearSearchString}> Clear </Button>

    <TextField  
      inputRef={inputRef} 
      name="searchStr"    
      onChange={(e) => setSearchTerm(e.target.value)}
     }
  </>
 )
}