Last active
February 6, 2020 18:29
-
-
Save bengrunfeld/5a6077c5758143eabac9f1188a31e5ab to your computer and use it in GitHub Desktop.
React Focus on Element on Load
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useRef, useState } from "react"; | |
const focus = (ref: Reference<HTMLInputElement | null>) => { | |
if (ref && ref.current) { | |
ref.current.focus(); | |
} | |
}; | |
// Step 1. Create a ref that can be used for focus | |
const inputEl = useRef<HTMLInputElement | null>(null); | |
// Step 2. setFocus on the input element | |
useEffect(() => focus(inputEl), []); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment