Search code examples
androidreactjsreact-nativehybrid-mobile-app

How do I pass initial props (or launchoptions) to first scene?


I am sending data from Android Native to React native by setting a simple prop in Android via the launchoptions.

I was successfully able to receive the initial props in the react-native module, but now when I am using StackNavigator like this :

const RootStack = createStackNavigator(
    { 
        home: Details,
        genre: Genre,
    },
    { 
        initialRouteName: 'home',
    }
);
const AwesomeProject = createAppContainer(RootStack);
export default AwesomeProject;

Now I am unable to use my Prop in the HomeScreen's constructor. How do I pass my initial props into the home screen?

The react-native version I am using is 0.58.4

Here's the full Code in React-Native :

import { 
  createStackNavigator, 
  createAppContainer 
} from 'react-navigation';

import Genre from './app/Genre';
import Details from './app/Details';

const RootStack = createStackNavigator(
    { 
        home: Details,
        genre: Genre,
    },
    { 
        initialRouteName: 'home',
    }
);

const AwesomeProject = createAppContainer(RootStack);
export default AwesomeProject;

Here's the Android code:

@Override
    protected ReactActivityDelegate createReactActivityDelegate() {
        return new ReactActivityDelegate(this, getMainComponentName()) {
            @Nullable
            @Override
            protected Bundle getLaunchOptions() {
                Bundle bundle = new Bundle();
                String str = MainActivity.getMovieID();
                bundle.putString("movie_id", str);
                return bundle;
            }
        };
    }

My problem is exactly same as this one: https://github.com/react-navigation/react-navigation/issues/634

But the problem is the solution given by the user is for an older version of react and in the new react-navigation-3 you must set up your app container directly, so his solution does not work.

Please help.


Solution

  • Finally got it to work and was successfully able to send initialProps from native android to react-native's first scene of StackNavigator like this:

    const StackNavigator = createStackNavigator(
        { 
            home:  {screen: Details},
            genre: {screen: Genre},
        },
        { 
            initialRouteName: 'home',
        }
    );
    
    const RootStack = createAppContainer(StackNavigator)
    
    export default class AwesomeProject extends Component {
        constructor(props){
            super(props)
        }
    
        render() {
        return <RootStack screenProps={this.props.movie_id} />;
      }
    }