Skip to content

Instantly share code, notes, and snippets.

@theptrk
Last active November 14, 2021 02:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theptrk/b0945adcfc434d0041f6bef277c8727b to your computer and use it in GitHub Desktop.
Save theptrk/b0945adcfc434d0041f6bef277c8727b to your computer and use it in GitHub Desktop.
This cheatsheet is for working with types in typescript react
/* Formatting dates */
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
// leave locale undefined (varies according to default locale)
new Date().toLocaleDateString(undefined, {
year: "numeric",
month: "2-digit",
day: "2-digit",
})
/* document event: keydown */
document.addEventListener("keydown", handleKeyDown);
const handleKeyDown = (e: KeyboardEvent) => {
// this can access e.key
}
/* createRef */
const myRef: React.RefObject<HTMLInputElement> = React.createRef()
/* list of createRef */
const myRef: Array<React.RefObject<HTMLInputElement>> = [React.createRef(), React.createRef()]
/* typing setState */
interface IDoc {
id: number,
title: string
}
const [docs, setDocs] = useState<Array<IDoc>>([]);
/*** Actions ***/
/* input onChange */
<input
onChange={handleInputChange}
/>
const handleInputChange(e: React.ChangeEvent<HTMLInputElement>) => {
// this can access e.target.value
}
/* input or textarea onChange onto an object */
const updateCreateForm = (
e:
| React.ChangeEvent<HTMLInputElement>
| React.ChangeEvent<HTMLTextAreaElement>
) => {
let newData: Record<string, string | boolean> = {};
newData[e.target.name] = e.target.value;
setCreateForm((oldCreateForm) => {
return Object.assign({}, oldCreateForm, newData);
});
};
const submitForm = (e: React.FormEvent) => {
e.preventDefault();
console.log("submit action");
};
<form onSubmit={submitForm}>
<h3>
<input type="text" />
<button>Save</button>
</h3>
</form>
/*** REACT ROUTER ***/
// https://reactrouter.com/web/guides/quick-start
// https://stackoverflow.com/questions/63660520/typescript-error-after-upgrading-version-4-useparams-from-react-router-dom-pr/64027431#64027431
let { topicId } = useParams<{ topicId: string }>();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment