Last active
December 2, 2020 03:48
-
-
Save steveruizok/f6d2815e8a757a4238220caa116c561e to your computer and use it in GitHub Desktop.
A utility function for getting the type-asserted value of a ref in React.
This file contains 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 * as React from "react" | |
import { getRef } from "./getRef" | |
export default function App() { | |
const rCanvas = React.useRef<HTMLCanvasElement>(null) | |
React.useEffect(() => { | |
const canvas = getRef(rCanvas) | |
canvas.width = window.innerWidth | |
canvas.width = window.innerHeight | |
}, []) | |
return ( | |
<div> | |
<canvas ref={rCanvas} /> | |
</div> | |
) | |
} |
This file contains 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 { MutableRefObject, RefObject } from "react" | |
function assert<T>(value: T | null | undefined): asserts value is T { | |
if (value === null || typeof value === "undefined") { | |
throw new Error("Ref assertion failed.") | |
} | |
} | |
export function getRef<T>(ref: MutableRefObject<T> | RefObject<T>): T { | |
assert(ref.current) | |
return ref.current | |
} |
https://gist.github.com/steveruizok/f6d2815e8a757a4238220caa116c561e#file-getref-ts-L11
should be
assert(...)
instead ofassertRef(...)
Thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://gist.github.com/steveruizok/f6d2815e8a757a4238220caa116c561e#file-getref-ts-L11
should be
assert(...)
instead ofassertRef(...)