Created
February 8, 2021 08:59
-
-
Save kayac-chang/647e36970c133eff58028e9f36415423 to your computer and use it in GitHub Desktop.
React Pattern
This file contains 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 { 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