Created
March 8, 2022 20:47
-
-
Save Cogentx/861a862922f2d2fe50ecce0a49d7104e to your computer and use it in GitHub Desktop.
React TypeScript useRef Hook
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 { useRef } from 'react'; | |
export default function InputBox() { | |
// before render `inputRef` is `null` | |
// after render `inputRef` is an Object with a `current` property | |
const inputRef = useRef<HTMLInputElement>(null); | |
const sendPost = async (e: any) => { | |
// prevent page refresh on submit | |
e.preventDefault(); | |
// only submit if message exists | |
if (!inputRef.current?.value) return; | |
/* Code to submit form data to backend */ | |
// clear input field after form submit | |
inputRef.current.value = ''; | |
}; | |
return ( | |
<div> | |
<form onSubmit={sendPost}> | |
<input | |
type="text" | |
ref={inputRef} | |
placeholder="What's on your mind?" | |
/> | |
<button onClick={sendPost} hidden type="submit"> | |
Submit | |
</button> | |
</form> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment