Common HTML element reference
// BEFORE
const htmlRef = useRef<HTMLDivElement>()
// AFTER
const htmlRef = useRef<ElementRef<'div'>>() // <-- such convenience
Common-ish forwarding Components that expect element references
const NormalComponent = forwardRef<HTMLDivElement, NormalProps>(
(props, ref) => <div ref={ref}>{/* ... */}</div>
)
// BEFORE
const innerHtmlRef = useRef<HTMLDivElement>()
return (
<NormalComponent ref={innerHtmlRef} />
)
// AFTER
const innerHtmlRef = useRef<ElementRef<typeof NormalComponent>>() // <-- well thats neat
return (
<NormalComponent ref={innerHtmlRef} />
)
Uncommon forwarding Components that expect imperative instance references (when ya need it, ya need it)
interface ImperitiveComponentActions {
doAction: (data: any) => void
}
const ImperativeComponent = forwardRef<ImperitiveComponentActions, NormalProps>(
(props, ref) => {
useImperativeHandle(ref, () => ({
doAction: (data) => handleDoAction(data)
}))
return <div>{/* ... */}</div>
}
)
// BEFORE
import { ImperativeComponent, ImperitiveComponentActions } from './component'
const instanceRef = useRef<ImperitiveRefValue>()
return (
<ImperativeComponent ref={instanceRef} />
)
// AFTER
import { ImperativeComponent } from './component'
const instanceRef = useRef<ElementRef<typeof ImperativeComponent>>() // <-- magic, wow
return (
<ImperativeComponent ref={innerHtmlRef} />
)