Skip to content

Instantly share code, notes, and snippets.

@Cogentx
Created March 8, 2022 20:47
Show Gist options
  • Save Cogentx/861a862922f2d2fe50ecce0a49d7104e to your computer and use it in GitHub Desktop.
Save Cogentx/861a862922f2d2fe50ecce0a49d7104e to your computer and use it in GitHub Desktop.
React TypeScript useRef Hook
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