Skip to content

Instantly share code, notes, and snippets.

@steveruizok
Last active December 2, 2020 03:48
Show Gist options
  • Save steveruizok/f6d2815e8a757a4238220caa116c561e to your computer and use it in GitHub Desktop.
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.
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>
)
}
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
}
@mathieudutour
Copy link

@steveruizok
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment