Skip to content

Instantly share code, notes, and snippets.

@adrianbrowning
Created April 19, 2023 07:46
Show Gist options
  • Select an option

  • Save adrianbrowning/c99f5b300043bb28db5e11d9228ac334 to your computer and use it in GitHub Desktop.

Select an option

Save adrianbrowning/c99f5b300043bb28db5e11d9228ac334 to your computer and use it in GitHub Desktop.
react-forwardref.tsx
// https://fettblog.eu/typescript-react-generic-forward-refs/
declare module "react" {
function forwardRef<T, P = {}>(
render: (props: P, ref: React.Ref<T>) => React.ReactElement | null
): (props: P & React.RefAttributes<T>) => React.ReactElement | null;
}
// Usage
// Just write your components like you're used to!
type ClickableListProps<T> = {
items: T[];
onSelect: (item: T) => void;
};
function ClickableListInner<T>(
props: ClickableListProps<T>,
ref: React.ForwardedRef<HTMLUListElement>
) {
return (
<ul ref={ref}>
{props.items.map((item, i) => (
<li key={i}>
<button onClick={(el) => props.onSelect(item)}>Select</button>
{item}
</li>
))}
</ul>
);
}
export const ClickableList = React.forwardRef(ClickableListInner);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment