Created
November 27, 2020 14:24
-
-
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
This file contains 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 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