Last active
February 2, 2021 12:22
-
-
Save dominictobias/e6c25657cf954e580249c09aa9c43082 to your computer and use it in GitHub Desktop.
Example of react-navigate and redux HOC for authenticated routes
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
/* | |
Example usage: | |
StackNavigator({ | |
Login: { screen: Login }, | |
Play: { screen: AuthBlockade(Play) }, | |
}, { | |
initialRouteName: 'Play', | |
}); | |
*/ | |
import React, { Component, PropTypes } from 'react'; | |
import { connect } from 'react-redux'; | |
import { NavigationActions } from 'react-navigation'; | |
const resetLoginAction = NavigationActions.reset({ | |
index: 0, | |
actions: [ | |
NavigationActions.navigate({ routeName: 'Login' }), | |
], | |
}); | |
const AuthBlockade = (ProtectedComponent) => { | |
class BlockadeComponent extends Component { | |
componentWillMount() { | |
if (!this.props.userAuthed) { | |
this.props.navigation.dispatch(resetLoginAction); | |
} | |
} | |
componentWillUpdate(nextProps) { | |
if (!nextProps.userAuthed) { | |
nextProps.navigation.dispatch(resetLoginAction); | |
} | |
} | |
render() { | |
return <ProtectedComponent {...this.props} />; | |
} | |
} | |
BlockadeComponent.propTypes = { | |
navigation: PropTypes.shape({ | |
dispatch: PropTypes.func.isRequired, | |
}).isRequired, | |
userAuthed: PropTypes.bool.isRequired, | |
}; | |
BlockadeComponent.navigationOptions = Component.navigationOptions; | |
const mapStateToProps = ({ auth }) => ({ | |
userAuthed: auth.userAuthed, | |
}); | |
return connect(mapStateToProps)(BlockadeComponent); | |
}; | |
export default AuthBlockade; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment