Skip to content

Instantly share code, notes, and snippets.

@skellock
Created May 8, 2017 13:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skellock/fb15c65079bb973490cf7aa370f6fca9 to your computer and use it in GitHub Desktop.
Save skellock/fb15c65079bb973490cf7aa370f6fca9 to your computer and use it in GitHub Desktop.
react-navigation + redux
// this will upgrade your current navigator to redux-aware one
import * as ReactNavigation from 'react-navigation'
import { connect } from 'react-redux'
import { pick } from 'ramda'
// here is our redux-aware smart component
function DrawerNavigatorContainer (props) {
const { dispatch, nav } = props
const navigation = ReactNavigation.addNavigationHelpers({
dispatch,
state: nav
})
return <DrawerNavigator navigation={navigation} />
}
// i'm a ramda fan, but you can use pure js if you'd like:
// const mapStateToProps = state = ({ nav: state.nav })
const mapStateToProps = pick(['nav'])
export default connect(mapStateToProps)(DrawerNavigatorContainer)
// completely optional, but here's a way to create some helper action creators you can call from your app.
import { NavigationActions } from 'react-navigation'
/**
* Creates an navigation action for dispatching to Redux.
*
* @param {string} routeName The name of the route to go to.
*/
const navigateTo = routeName => () => NavigationActions.navigate({ routeName })
export const navigateToAccount = navigateTo('account')
export const navigateToChangePassword = navigateTo('changePassword')
import { NavigationActions } from 'react-navigation'
// i used a drawer, you can just use a stack
import { DrawerNavigator } from '../../ui/navigation/drawer-navigator/drawer-navigator'
const { navigate } = NavigationActions
const { getStateForAction } = DrawerNavigator.router
const initialState = getStateForAction(
navigate({ routeName: 'dashboardStack' }) // my default "screen"
)
export function reducer (state = initialState, action) {
return DrawerNavigator.router.getStateForAction(action, state) || state
}
import { combineReducers } from 'redux'
import { reducer as nav } from './navigation/navigation.reducer'
// add `nav` into your root reducer
export default () => combineReducers({
nav // you only see 1 thing here, but your app will have many reducers.
})
// then to trigger an action
import React, { PureComponent } from 'react'
import { connect } from 'react-redux'
import { Button } from 'react-native'
class SomeButton extends PureComponent {
render () {
return (
<Button
onPress={this.props.navigateToAccount}
title='OMG LETS GO!!!!!!!'
/>
)
}
}
const mapDispatchToProps = dispatch => ({
navigateToAccount: () => dispatch(navigateToAccount())
})
export default connect(null, mapDispatchToProps)(SomeButton)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment