Skip to content

Instantly share code, notes, and snippets.

@loklaan
Last active February 2, 2024 04:19
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 loklaan/f9e77484619b1e734110472c5aff4e1f to your computer and use it in GitHub Desktop.
Save loklaan/f9e77484619b1e734110472c5aff4e1f to your computer and use it in GitHub Desktop.
Using the ElementRef<> type util

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} />
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment