Last active
July 14, 2017 18:21
-
-
Save petejodo/4f9e87bca34ac7c0924bf674209bb7af to your computer and use it in GitHub Desktop.
Inject Theme into Component
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
// @flow | |
import classnames from 'classnames'; | |
type FunctionComponent<P, C> = (props: P, context: C) => ?React$Element<any>; | |
type ClassComponent<D, P, S> = Class<React$Component<D, P, S>>; | |
type ThemeType = { [className: string]: string }; | |
type ThemePropType = { theme: ThemeType }; | |
declare function mergeTheme<P: { theme: * }, V: $PropertyType<P, 'theme'>>( | |
BaseComponent: ClassComponent<*, P, *>, | |
injectedTheme: V | |
): FunctionComponent<$Diff<P, { theme: V }>, *>; | |
declare function mergeTheme<P: { theme: * }, V: $PropertyType<P, 'theme'>>( | |
BaseComponent: FunctionComponent<P, *>, | |
injectedTheme: V | |
): FunctionComponent<$Diff<P, { theme: V }>, *>; | |
function mergeTheme(BaseComponent, injectedTheme) { | |
const ThemedComponent = ownProps => <BaseComponent {...ownProps} theme={injectedTheme} />; | |
ThemedComponent.displayName = `Themed(${BaseComponent.displayName})`; | |
return ThemedComponent; | |
} | |
export default mergeTheme; |
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 React from 'react'; | |
import mergeTheme from './mergeTheme'; | |
// == TEST CODE ========================================== | |
type SomeComponentTheme = { | |
someClass: string | |
}; | |
type SomeComponentProps = { | |
someProp: string, | |
theme: SomeComponentTheme | |
}; | |
const SomeComponent = (props: SomeComponentProps) => { | |
return <div className={props.theme.someClass}>{props.someProp}</div>; | |
}; | |
const ThemedComponentOne = mergeTheme(SomeComponent, { someClass: 'poop' }); | |
const ThemedComponentTwo = mergeTheme(SomeComponent, { anotherClass: 'poop '}); // should error but doesn't | |
const ThemedComponentThree = mergeTheme(SomeComponent, { someClass: 1 }); // should error but doesn't |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment