Skip to content

Instantly share code, notes, and snippets.

@sekoyo
Last active February 2, 2021 12:22
Show Gist options
  • Save sekoyo/e6c25657cf954e580249c09aa9c43082 to your computer and use it in GitHub Desktop.
Save sekoyo/e6c25657cf954e580249c09aa9c43082 to your computer and use it in GitHub Desktop.
Example of react-navigate and redux HOC for authenticated routes
/*
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