Skip to content

Instantly share code, notes, and snippets.

@mahdiyazdani
Created November 27, 2020 14:24
Show Gist options
  • Save mahdiyazdani/c5d6b27046584cea708e8f517910bd3a to your computer and use it in GitHub Desktop.
Save mahdiyazdani/c5d6b27046584cea708e8f517910bd3a to your computer and use it in GitHub Desktop.
Focus an input control upon first render, using `useEffect` combined with the `useRef` hook
import React, { useEffect, useState, useRef } from "react";
import ReactDOM from "react-dom";
function App() {
// Store a reference to the input's DOM node
const inputRef = useRef();
const [value, setValue] = useState("");
useEffect(
() => {
// This runs AFTER the first render,
// so the ref is set by now.
console.log("render");
// inputRef.current.focus();
},
[inputRef]
);
return (
<input
ref={inputRef}
value={value}
onChange={e => setValue(e.target.value)}
/>
);
}
ReactDOM.render(<App />, document.querySelector("#root"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment