Last active
February 1, 2019 08:42
-
-
Save akx/64e0d1372354be20ffe4001a3cae04c1 to your computer and use it in GitHub Desktop.
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
// h/t @japsu for the idea. had to type it. | |
import React from "react"; | |
function connect<C, P>( | |
ContextClass: React.Context<C>, | |
propName: keyof P, | |
): (( | |
component: React.FunctionComponent<P> | React.ComponentClass<P>, | |
) => React.FunctionComponent<P>) { | |
return WrappedComponent => (props: P) => ( | |
<ContextClass.Consumer> | |
{value => <WrappedComponent {...{ ...props, [propName]: value }} />} | |
</ContextClass.Consumer> | |
); | |
} | |
function connect2<C, P>( | |
ContextClass: React.Context<C>, | |
propName: keyof P, | |
WrappedComponent: React.FunctionComponent<P> | React.ComponentClass<P>, | |
): React.FunctionComponent<P> { | |
return (props: P) => ( | |
<ContextClass.Consumer> | |
{value => <WrappedComponent {...{ ...props, [propName]: value }} />} | |
</ContextClass.Consumer> | |
); | |
} | |
interface IUserContext { | |
id?: string; | |
name?: string; | |
} | |
const UserContext = React.createContext<IUserContext>({}); | |
interface UserInfoProps { | |
user: IUserContext; | |
} | |
const UserInfo: React.FunctionComponent<UserInfoProps> = ({ user }) => | |
user.id ? <>ohai {user.name}</> : null; | |
const ConnectedUserInfo = connect<IUserContext, UserInfoProps>( | |
UserContext, | |
"user", | |
)(UserInfo); | |
const ConnectedUserInfo2 = connect2<IUserContext, UserInfoProps>( | |
UserContext, | |
"user", | |
UserInfo, | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment