Last active
November 5, 2017 20:20
-
-
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.
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
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