Created
February 27, 2021 10:31
-
-
Save JaysonChiang/345c71724f4da1c774ea89fe6eed2fe2 to your computer and use it in GitHub Desktop.
React Refs with TypeScript
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 { useState, useRef, useEffect } from 'react'; | |
const Search: React.FC = () => { | |
const inputRef = useRef<HTMLInputElement | null>(null); | |
const [name, setName] = useState(''); | |
useEffect(() => { | |
if (!inputRef.current) { | |
return; | |
} | |
inputRef.current.focus(); | |
}, []); | |
return ( | |
<div> | |
<input | |
ref={inputRef} | |
value={name} | |
onChange={(e) => setName(e.target.value)} | |
/> | |
<div>{name}</div> | |
</div> | |
); | |
}; | |
export default Search; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment