Skip to content

Instantly share code, notes, and snippets.

@bengrunfeld
Last active February 6, 2020 18:29
Show Gist options
  • Save bengrunfeld/5a6077c5758143eabac9f1188a31e5ab to your computer and use it in GitHub Desktop.
Save bengrunfeld/5a6077c5758143eabac9f1188a31e5ab to your computer and use it in GitHub Desktop.
React Focus on Element on Load
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