Last active
April 30, 2024 16:01
-
-
Save karol-majewski/d2fe4a9f60af8f8b692962f06ea13e32 to your computer and use it in GitHub Desktop.
Functional composition for React props
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 * as React from 'react'; | |
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>; | |
/** | |
* Supplies default props. | |
*/ | |
export function withDefaults<T extends React.ComponentType<any>, U extends Partial<React.ComponentProps<T>>>( | |
Component: T, | |
defaults: U, | |
): React.FunctionComponent<Omit<React.ComponentProps<T>, keyof U> & Partial<U>> { | |
// Returning `<Component { ...defaults} {...props } />;` gives an error. | |
// @see https://github.com/Microsoft/TypeScript/issues/14729 | |
return props => React.createElement(Component, { ...defaults, ...props }); | |
} | |
/** | |
* Partially applies props. | |
*/ | |
export function withProps<T extends React.ComponentType<any>, U extends Partial<React.ComponentProps<T>>>( | |
Component: T, | |
defaults: U, | |
): React.FunctionComponent<Omit<React.ComponentProps<T>, keyof U>> { | |
return props => React.createElement(Component, { ...defaults, ...props }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: