Skip to content

Instantly share code, notes, and snippets.

@JaysonChiang
Created February 27, 2021 10:31
Show Gist options
  • Save JaysonChiang/345c71724f4da1c774ea89fe6eed2fe2 to your computer and use it in GitHub Desktop.
Save JaysonChiang/345c71724f4da1c774ea89fe6eed2fe2 to your computer and use it in GitHub Desktop.
React Refs with TypeScript
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