Search code examples
reactjsreact-nativereduxreact-reduxreact-navigation

What is the shortest way to add redux to react-navigation?


I'm integrating redux to my react-native application. Want to introduce Provider and to wrap screens in it. I'm using such constructions to register new screen:

Navigation.registerComponent('Login', () => LoginScreen);

As I see in documentation I need to wrap every component in <Provider store={store}>

And I'm just wondering if exist another way to do this, because if I have 10 screens(for example) in my app, I need to wrap them in provider ten times. I'll get code duplicates, but htis is not good


Solution

  • You can achieve this by creating an AppContainer component with all the components and wrap the AppContainer component inside the Provider.

    import React, { Component } from "react";
    import { createAppContainer } from "react-navigation";
    import { createStackNavigator } from "react-navigation-stack";
    import { Provider as StoreProvider } from "react-redux";
    
    const MainNavigator = createStackNavigator({
     firstcomponentpath: FirstComponent,
     secondcomponentpath: SecondComponent
    )}
    
    const AppContainer = createAppContainer(MainNavigator);
    
    export default class App extends Component {
    super(props);
    this.state = {};
    }
    
    render() {
    return (
    <Provider store={store}>
    <AppConatiner />
    </Provider>
    )}