Navigate to new component after dispatch from mapDispatchToProps

After setting the language for my app by clicking the English or French button, I need to navigate to the next screen. How do I call this.props.navigation.navigate('HomeScreen') directly after a dispatch?

I tried putting both in a function and calling it from onPress, but that didn't work.

LanguageScreen.js

<Button
 title="English"
 onPress={this.props.english}
 />
 <Button
 title="Français"
 onPress={this.props.french}
 />

LanguageContainer.js

import React, { Component } from 'react';
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux';
import LanguageScreen from '../screens/LanguageScreen.js';

const mapStateToProps = (state, props) => ({
  language: state.language
})

const mapDispatchToProps = (dispatch) => ({
  french: () => {
    dispatch({ type: 'FRENCH' });
  },
  english: () => {
    dispatch({ type: 'ENGLISH' });
  },
})

export default connect(mapStateToProps, mapDispatchToProps)(LanguageScreen)

store.js

import { createStore } from 'redux'

export const language = (state = 'english', action) => {
  switch (action.type) {
  case 'FRENCH':
    return 'french';
  case 'ENGLISH':
    return 'english';
  default:
    return state;
  }
}

let store = createStore(language);

export default store;

1 answer

  • answered 2018-01-11 19:45 Bartek Fryzowicz

    mapDispatchToProps accepts ownProps as second argument so assuming your component receives navigate prop you can try something like this:

    const mapDispatchToProps = (dispatch, ownProps) => ({
      french: () => {
        dispatch({ type: 'FRENCH' });
        ownProps.navigation.navigate('HomeScreen');
      },
      english: () => {
        dispatch({ type: 'ENGLISH' });
        ownProps.navigation.navigate('HomeScreen');
      },
    }