Skip to content

Latest commit

 

History

History
36 lines (25 loc) · 924 Bytes

programatically-transfer-focus.md

File metadata and controls

36 lines (25 loc) · 924 Bytes

Programatically Transfer Focus

Category: React

Focus can be transferred programmatically between React components by calling focus() on a ref.

This TIL assumes the use of TypeScript.

Assume you have a text input field. Create a ref to it and a method to transfer focus:

const searchInputRef = useRef<HTMLInputElement>(null);

const transferFocus = () => {
  if (searchInputRef.current !== null) {
    searchInputRef.current.focus();
  }
  console.log('Transferring focus to search input');
}

Assign the ref to the text input field:

<input ref={searchInputRef}>
  // etc
</input>

Transfer focus using the following:

transferFocus();

Note: You must specify the type for the ref (for example HTMLInputElement), otherwise the TypeScript compiler will complain about a potential null reference showing an error message of Object is possibly null.