Skip to content

Instantly share code, notes, and snippets.

@Southclaws
Last active November 5, 2017 20:20
Show Gist options
  • Save Southclaws/f002603d317dd0274ceec2796152b745 to your computer and use it in GitHub Desktop.
Save Southclaws/f002603d317dd0274ceec2796152b745 to your computer and use it in GitHub Desktop.
I wrestled with this for a while so I figured I'd share it. It's a TypeScript implementation of the example "auth workflow" from the React Router docs, it's effectively the same concept just spiced up with types and it's embedded into a class so it can access app state easily.
class App extends React.Component<{}, AppState> {
// IfLoggedIn is a TypeScript version of:
// https://reacttraining.com/react-router/web/example/auth-workflow
// it's just a stateless component that takes path and component (similar to <Route>)
// and renders the component if the user is logged in, if not, it redirects to /login
IfLoggedIn = (thisProps: { path: string; component: Function }) => {
return (
<Route
render={props =>
this.state.loggedIn ? (
thisProps.component
) : (
<Redirect
to={{
pathname: "/login",
state: { from: props.location }
}}
/>
)}
/>
);
};
render() {
return (
<Router>
<this.IfLoggedIn
path="/upload"
component={Upload}
/>
</Router>)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment