Skip to content

Instantly share code, notes, and snippets.

@amackintosh
Created November 1, 2017 20:55
Show Gist options
  • Save amackintosh/4d4fd87ddd327188aa06e07403606b52 to your computer and use it in GitHub Desktop.
Save amackintosh/4d4fd87ddd327188aa06e07403606b52 to your computer and use it in GitHub Desktop.
requireAuth Higher-order Component for React Native
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { NavigationActions } from 'react-navigation'
export default function (ComposedComponent) {
class Authentication extends Component {
componentWillMount() {
if (!this.props.isAuthenticated) {
return this.props.navigation.dispatch(NavigationActions.reset({
index: 0,
key: null,
actions: [NavigationActions.navigate({ routeName: 'Login' })]
}))
}
}
componentWillReceiveProps(nextProps) {
if (!nextProps.isAuthenticated) {
return this.props.navigation.dispatch(NavigationActions.reset({
index: 0,
key: null,
actions: [NavigationActions.navigate({ routeName: 'Login' })]
}))
}
}
render() {
if (!this.props.isAuthenticated) return null
return (
<ComposedComponent {...this.props} />
)
}
}
const mapStateToProps = ({ auth: { isAuthenticated } }) => ({ isAuthenticated })
return connect(mapStateToProps, null)(Authentication)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment