Last active
September 23, 2019 17:29
-
-
Save slightlytyler/289ad9fb48ae6cb69f1470a4a7a78955 to your computer and use it in GitHub Desktop.
The power of a branch
This file contains hidden or 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
// Basic branch | |
const Branch = props => { | |
if (props.condition) return props.renderLeft(); | |
return props.renderRight(); | |
}; | |
Branch.defaultProps = { | |
renderRight: () => null, | |
}; | |
// Auth branch, only render something if user is authenticated | |
// or render a fallback | |
const AuthBranch = props => { | |
const { isAuthenticated } = useAuth(); | |
return ( | |
<Branch | |
{...props} | |
condition={isAuthenticated} | |
/> | |
); | |
}; | |
const AppHeader = props => ( | |
<header> | |
<nav>{...}</nav> | |
<AuthBranch | |
renderLeft={() => <Avatar />} | |
renderRight={() => <LoginButton />} | |
/> | |
</header | |
); | |
// Auth route, only render a route if user is authenticated | |
// otherwise redirect to "/login" | |
const AuthRoute = props => ( | |
<AuthBranch | |
renderLeft={() => <Route {...props} />} | |
renderRight={() => <Redirect to="/login" />} | |
/> | |
); | |
const SomeRoutes = () => ( | |
<Switch> | |
<AuthRoute exact path="/" component={HomePage} /> | |
<Route path="/login" component={LoginPage} /> | |
</Switch> | |
); | |
// Wrapper branch, wrap children in a wrapper depending | |
// on a condition | |
const WrapIf = props => ( | |
<Branch | |
condition={props.condition} | |
renderLeft={() => props.renderWrapper(props.children)} | |
renderRight={() => React.Children.only(props.children) | |
? props.children | |
: <React.Fragment>{props.children}</React.Fragment> | |
} | |
/> | |
); | |
const NavItem = props => ( | |
<WrapIf | |
condition={props.tooltip} | |
renderWrapper={children => ( | |
<Tooltip message={props.tooltip}>{children}</Tooltip> | |
)} | |
> | |
<li>{...}</li> | |
</WrapIf> | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment