Automatically focus on input using Refs in Typescript/React

My brain is quite small, and absorbs information about as well as a rock absorbs water. As a result, it requires lengthy, comprehensive, example-filled explanations of concepts before new ideas stick. This is one such explanation.

Problem

Solution

useRef

useEffect

The custom hook

The hook:

import { useRef, useEffect } from "react"export const useFocus = () => {
const ref = useRef<HTMLInputElement>(null)

useEffect(() => {
ref.current?.focus()
})
return ref }

The hook being used in a component like so:

export const NewItemForm = () => {
const [text, setText] = useState("")
const inputRef = useFocus()
return (
<NewItemFormContainer>
<Input
ref={inputRef}
value={text}
onChange={e => setText(e.target.value)}
/>
</NewItemFormContainer>
)
}

The explanation:

  • Looking at the second code-block, we are using the custom hook useFocus as the ref of the rendered Input
  • From the first code block, we see that what useFocus returns is a ref that has been focused
  • So, we could think of this trick as the following command: “Create a ref that has been focused, and now make the ref of this input DOM element be that focused ref. Therefore the input is now focused”

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store