Created
March 31, 2023 10:37
-
-
Save BalogunofAfrica/15e3ed757b6dcb730e106cc7623ddea0 to your computer and use it in GitHub Desktop.
Simple API for using FlashList as Scrollview
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { FlashList, FlashListProps } from "@shopify/flash-list"; | |
import React, { forwardRef, ReactElement } from "react"; | |
type ListProps<T> = Omit<FlashListProps<T>, "children"> & { as?: "list" }; | |
type ScrollViewProps<T> = Omit< | |
FlashListProps<T>, | |
"children" | "data" | "renderItem" | |
> & { | |
as?: "scroll-view"; | |
children: React.ReactNode | React.ReactNode[]; | |
}; | |
export type ListRendererProps<T> = ListProps<T> | ScrollViewProps<T>; | |
export type ListRendererRefType<T> = FlashList<T>; | |
function ListComponent<T>( | |
{ | |
as = "list", | |
bounces = false, | |
showsHorizontalScrollIndicator = false, | |
showsVerticalScrollIndicator = false, | |
...rest | |
}: ListRendererProps<T>, | |
ref: React.Ref<ListRendererRefType<T>>, | |
) { | |
if (as === "scroll-view") { | |
const props = rest as ScrollViewProps<T>; | |
return ( | |
<FlashList | |
data={ | |
(Array.isArray(props.children) | |
? props.children | |
: [props.children]) as T[] | |
} | |
renderItem={({ item }) => <>{item}</>} | |
{...{ | |
bounces, | |
ref, | |
showsHorizontalScrollIndicator, | |
showsVerticalScrollIndicator, | |
}} | |
{...props} | |
/> | |
); | |
} | |
return ( | |
<FlashList | |
{...{ | |
bounces, | |
ref, | |
showsHorizontalScrollIndicator, | |
showsVerticalScrollIndicator, | |
}} | |
{...(rest as ListProps<T>)} | |
/> | |
); | |
} | |
export const ListRenderer = forwardRef(ListComponent) as <T>( | |
props: ListRendererProps<T> & { ref?: React.Ref<ListRendererRefType<T>> }, | |
) => ReactElement; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment