hand sketched logo of electrons orbiting a nucleus

TIL: Make forwardRef Better

Option 1: Create fixedForwardRef function

function fixedForwardRef<T, P = {}>(
  render: (props: P, ref: React.Ref<T>) => React.ReactNode,
): (props: P & React.RefAttributes<T>) => React.ReactNode {
  return forwardRef(render) as any;
}

fixedForwardRef comes from Matt Pocock and is a bit more preferred as it won't leak into any code that imports your code.

Option 2: Override Reacts ForwardRef type

declare module 'react' {
  function forwardRef<T, P = {}>(
    render: (props: P, ref: React.Ref<T>) => React.ReactNode,
  ): (props: P & React.RefAttributes<T>) => React.ReactNode;
}

Here is a blog post explaining all this from the creator of this code Stefan Baumgartner

References

TIL: HOC needs ReactNode to be generic

React,

🤓 Today I Learned,

TypeScript

This is the same trick we used to get nicer forwardRef here.