Search code examples
react-nativereact-native-router-flux

How to use a variable in Actions.SCENE_KEY (react native router flux)


Forgive me if this is something simple i'm overlooking. I'm fairly new to programming, much newer to React and React Native.

I'm building a simple navigation drawer.

The drawer displays a Menu component which has a renderMenuItem(item) function which returns the following.

<Button onPress={() => this._onItemSelect(item)} style={styles.navItem} >{item}</Button>

It's responsible for returning the correctly labeled button to the render function.

The problem I'm having is when it gets to the onItemSelect funtion,

_onItemSelect(item) {
    //  handle action to render the new page!

    Actions.item      // Won't work
    //Actions.Page2     // Hardcoding the scene here won't work either
    );

I can't get it to actually display the new scene when the button is pressed. If I were to hardcode the scene into the onPress() function in the button, I can get it to work. For example:

<Button onPress={Actions.Page2} style={styles.navItem} >{item}</Button>

Obviously, that won't work. What I need is to be able to use item in either of the functions, the renderMenuItem(item) funtion or the onItemSelect(item) function.

Thank you. I've been wrecking my brain since last night trying to figure this one out.


Solution

  • The problem is that Actions.SCENE_KEY is a function that you can call, and when doing so the navigator will perform the action. It works when you do <Button onPress={Actions.Page2} because the button takes a function reference as the onPress property and it calls it for you when appropriate. You just have to change your code to:

    _onItemSelect(item) {
        //  handle action to render the new page!
    
        Actions.Page2();
    );
    

    Also, since you depend on the value of item, you can pass it as a prop, to the component, like this:

    _onItemSelect(item) {
        //  handle action to render the new page!
    
        Actions.Page2({item: item});
    );
    

    Then, your next screen will receive the usual props plus a new one called item with the value that you passed.