Skip to content

Instantly share code, notes, and snippets.

@akx
Last active February 1, 2019 08:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akx/64e0d1372354be20ffe4001a3cae04c1 to your computer and use it in GitHub Desktop.
Save akx/64e0d1372354be20ffe4001a3cae04c1 to your computer and use it in GitHub Desktop.
// 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