Search code examples
react-nativereact-native-navigation-v2

Is there a way to read the options before use the mergeOptions function in react native navigation v2?


Is there a way to read the options before using the mergeOptions function. I'm trying to add a sideMenu that opens and closes with the same button. But to handle that logic, Instead of making use of redux, I want to read the options before the merge, so I can simply do something like visible: !pastVisible.

navigationButtonPressed({ buttonId }) {
    Navigation.mergeOptions(this.props.componentId, {
        sideMenu: {
            'left': {
                visible: false
            }
        }
    });
    console.log(`Se presiono ${buttonId}`);
}

So basically I want to read the value of the visible option before changed it.


Solution

  • By now, I can only achieve this using redux.

    import React, {Component} from 'react';
    import {View, Text} from 'react-native';
    import { Navigation } from 'react-native-navigation';
    
    import { connect } from 'react-redux';
    import { toggleSideMenu } from './../../store/actions/index';
    
    class SideDrawer extends Component {
    
        constructor(props) {
            super(props);
            Navigation.events().registerComponentDidDisappearListener(({ componentId }) => {
                this.props.toggleSideMenu(false);
            });
        }
    
        render() {
            return (
                <View>
                    <Text>This is the sidedrawer</Text>
                </View>
            );
        }
    
    }
    
    const mapDispatchToProps = dispatch => {
        return {
            toggleSideMenu: (visible) => dispatch(toggleSideMenu(visible))
        };
    };
    export default connect(null, mapDispatchToProps)(SideDrawer);
    

    Then I just add the listeners to the sidemenu component. Depending on the case, I update the current state of the component (visible or not).

    Finally on the components where I want to use the side drawer button I just implement the navigationButtenPressed method. Then I just call the reducer to know the current visible state and toggled it.

    navigationButtonPressed({ buttonId }) {
        const visible = !this.props.sideMenu;
        Navigation.mergeOptions(this.props.componentId, {
            sideMenu: {
                'left': {
                    visible: visible
                }
            }
        });
        this.props.toggleSideMenu(visible);
    }
    

    If there is a more easy way to achieve this I'll be glad to know about it.