Skip to content

Instantly share code, notes, and snippets.

@kayac-chang
Created February 8, 2021 08:59
Show Gist options
  • Save kayac-chang/647e36970c133eff58028e9f36415423 to your computer and use it in GitHub Desktop.
Save kayac-chang/647e36970c133eff58028e9f36415423 to your computer and use it in GitHub Desktop.
React Pattern
import { ReactNode, isValidElement, PropsWithChildren } from "react";
type Props<T> = Pick<PropsWithChildren<T>, Exclude<keyof T, "children">>;
function isFunction<T, R>(instance: any): instance is (props: T) => R {
return typeof instance === "function";
}
export default function RenderProps<T>({
children,
...props
}: PropsWithChildren<T>) {
return (
<>
{isValidElement(children)
? children
: isFunction<Props<T>, ReactNode>(children)
? children(props)
: undefined}
</>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment