Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Generic Component with forwarded ref. #106

Copy link
Copy link
Closed
@andrewgreenh

Description

@andrewgreenh
Issue body actions

Hello everyone,

today I stumbled across the following problem:

I want to build a List Component that has a generic prop . From the outside you can pass a ref to the List, to access a scrollToItem(item: TItem). Since I want to use hooks, I need to use React.forwardRef, which does not allow to return a generic function.

This is my attempt of solving, but I feel like there could be something less verbose and repetitive.

type ListRef<ItemType> = {
  scrollToItem: (item: ItemType) => void;
};

type ListProps<ItemType> = {
  items: ItemType[];
};

const List = forwardRef(function List<ItemType>(props: ListProps<ItemType>) {
  useImperativeHandle<ListRef<ItemType>, ListRef<ItemType>>(ref, () => ({
    scrollToItem: (item: ItemType) => undefined
  }));

  return null;
}) as <ItemType>(
  p: ListProps<ItemType> & { ref: Ref<ListRef<ItemType>> }
) => ReactElement<any> | null;

let ref = useRef<ListRef<number>>(null);

<List items={[1, 2, 3]} ref={ref} />;

Metadata

Metadata

Assignees

No one assigned

    Labels

    wontfixThis will not be worked onThis will not be worked on

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.