Skip to content

Instantly share code, notes, and snippets.

@jankalfus
Last active October 24, 2017 10:21
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jankalfus/ccb0d0b4023cb6ab3b4aee4e49f4590b to your computer and use it in GitHub Desktop.
Save jankalfus/ccb0d0b4023cb6ab3b4aee4e49f4590b to your computer and use it in GitHub Desktop.
import React from "react"
import * as ReactNavigation from "react-navigation"
import { connect } from "react-redux"
import AppNavigation, { isDrawerOpen } from "./AppNavigation"
import { BackHandler } from "react-native"
import PropTypes from "prop-types"
class ReduxNavigation extends React.Component {
static propTypes = {
dispatch: PropTypes.func.isRequired,
nav: PropTypes.object.isRequired,
}
_shouldCloseApp = () => this.props.nav.index === 0
_goBack = () => this.props.dispatch(ReactNavigation.NavigationActions.back())
_closeDrawer = () => this.props.dispatch(ReactNavigation.NavigationActions.navigate({
routeName: "DrawerClose"
}))
_handleBackPress = () => {
if (isDrawerOpen(this.props.nav)) {
this._closeDrawer()
return true
}
if (this._shouldCloseApp()) {
return false
}
this._goBack()
return true
}
componentWillMount() {
BackHandler.addEventListener("hardwareBackPress", this._handleBackPress)
}
componentWillUnmount() {
BackHandler.removeEventListener("hardwareBackPress", this._handleBackPress)
}
render() {
const { dispatch, nav } = this.props
const navigation = ReactNavigation.addNavigationHelpers({
dispatch,
state: nav
})
return <AppNavigation navigation={navigation} />
}
}
const mapStateToProps = state => ({ nav: state.nav })
export default connect(mapStateToProps)(ReduxNavigation)
@jankalfus
Copy link
Author

BTW isDrawerOpen is a simple function, which extracts info from nav and returns a boolean:
const isDrawerOpen = (nav) => nav.routes[0].index === 1

Note that the path might be different for you, based on the way you hooked up your navigators.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment