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
I have a react component that appears after a button click. I wish to automatically focus on the react component when it loads, so I can immediately start typing.
Solution
We will use two hooks to construct a custom hook that can be applied to the input component, causing the focus upon load.
useRef
This is a simple little hook that, in this case, will let us explicitly refer to a DOM element that we create (the input box).
useEffect
UseEffect lets us trigger a function whenever certain dependencies change. That sounds useful for our purposes.
The custom hook
Here I create a hook, and then I apply it to a rendered element in a component. I believe that the best way to explain this is to present the entire code up-front, then describe it in parts.
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 renderedInput
- 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”