1
0
mirror of https://github.com/ascribe/onion.git synced 2025-01-05 11:25:09 +01:00
onion/js/utils/react_utils.js
Brett Sun b5eda1cdd2 Inject isLoggedIn through withCurrentUser
Makes checking for logged in status less error prone than always using
`currentUser.email` or `currentUser.username`.
2016-06-07 14:56:40 +02:00

35 lines
1.2 KiB
JavaScript

import React from 'react';
import { currentUserShape } from '../components/prop_types';
/**
* Taken from react-router (https://github.com/reactjs/react-router/blob/master/modules/withRouter.js)
* FIXME: should be put into react-component's utils
*/
export function getDisplayName(WrappedComponent) {
return WrappedComponent.displayName || WrappedComponent.name || 'Component';
}
/**
* Similar to react-router's `withRouter`, this injects the `currentUser` from the Component's
* context into the Component as a prop. It also injects whether the user's logged in or not as
* `isLoggedIn`.
*
* @param {Component} Component Component to inject `context.currentUser` and `isLoggedIn` into
* @return {Component} Wrapped component
*/
export function withCurrentUser(Component) {
const contextTypes = {
currentUser: currentUserShape.isRequired
};
const WithCurrentUser = (props, { currentUser }) => (
<Component {...props} currentUser={currentUser} isLoggedIn={!!currentUser.email} />
);
WithCurrentUser.displayName = `WithCurrentUser(${getDisplayName(Component)})`;
WithCurrentUser.contextTypes = contextTypes;
return WithCurrentUser;
}