Jo Momma
Jo Momma

Reputation: 1307

How to determine active route in DrawerNavigator to tint the active menu Item and close the drawer

I am using the React Navigation library. I have written a custom drawer menu and added it to the contentComponent config for my navigator. I don't know how to determine which page/screen is active from within the custom menu. Here is my code for the DrawerNavigator:

const DrawerNavigator = createDrawerNavigator({
    "Search Locations": {
        screen: SearchLocationsScreen,
    },
    "About": {
        screen: AboutScreen
    },
    "Favorites": {
        screen: FavoritesScreen
    },
    "Sign In": {
        screen: SignIn
    },
}, {
    contentComponent: props => <CustomDrawerComponent {...props} />
});

It may be important to note that my DrawerNavigator is nested inside a StackNavigator. I export my navigation options to a separate file like this:

export default (navigation) => {
    const {state} = navigation;
    let navOptions = {};

    if(state.index === 0){
        navOptions.headerRight = (
            <TouchableOpacity>
                <MaterialIcons
                    name="my-location"
                    size={32}
                    color="#fff"
                    style={{paddingRight: 10}} />
            </TouchableOpacity>
        )
    }

        if (state.isDrawerOpen){
        navOptions.headerLeft = (
            <>
                <StatusBar barStyle='light-content'/>
                <TouchableOpacity onPress={() => {
                    navigation.dispatch(DrawerActions.toggleDrawer())
                }}>
                    <Ionicons name="ios-close" style={styles.menuClose} size={38} color={'#fff'}/>
                </TouchableOpacity>
            </>
        )
    } else {
        navOptions.headerLeft = (
            <>
                <StatusBar barStyle='light-content'/>
                <TouchableOpacity onPress={() => {
                    navigation.dispatch(DrawerActions.toggleDrawer())
                }}>
                    <Ionicons name="ios-menu" style={styles.menuOpen} size={32} color={'#fff'}/>
                </TouchableOpacity>
            </>
        )
    }

    return navOptions;
};

and I assign these options like this:

const MainStackNavigator = createStackNavigator({
    DrawerNavigator: {
        screen: DrawerNavigator,
        navigationOptions: ({navigation}) => configureDrawerOptions(navigation)
    }
}, {
    defaultNavigationOptions: configureDefaultStackNavOptions
});

My custom DrawerMenu looks like this:

const DrawerMenu = (props) => {

    // let routes = props.navigation.state.routes;

    const navigateToScreen = (route) => () => {

        const navAction = NavigationActions.navigate({
            routeName: route
        });
        props.navigation.dispatch(navAction);
    };

    return (
        <ScrollView style={styles.root}>

            <View style={styles.rowContainer}>
                <TouchableOpacity onPress={navigateToScreen('Search Locations')}>
                    <View style={styles.row}>
                        <MaterialIcons name='location-searching' style={styles.icon} size={30}/>
                        <Text style={styles.label}>Search Locations</Text>
                    </View>
                </TouchableOpacity>
            </View>

            <View {...props} style={styles.rowContainer}>
                <TouchableOpacity onPress={navigateToScreen('About')}>
                    <View style={styles.row}>
                        <MaterialIcons name='info-outline' style={styles.icon} size={30}/>
                        <Text style={styles.label}>About</Text>
                    </View>
                </TouchableOpacity>
            </View>

            <View {...props} style={styles.rowContainer}>
                <TouchableOpacity onPress={navigateToScreen('Favorites')}>
                    <View style={styles.row}>
                        <MaterialIcons name='favorite-border' style={styles.icon} size={30}/>
                        <Text style={styles.label}>Favorites</Text>
                    </View>
                </TouchableOpacity>
            </View>

            <View {...props} style={styles.rowContainer}>
                <TouchableOpacity onPress={navigateToScreen('Sign In')}>
                    <View style={styles.row}>
                        <Ionicons name='md-log-in' style={styles.icon} size={30}/>
                        <Text style={styles.label}>Sign In</Text>
                    </View>
                </TouchableOpacity>
            </View>

        </ScrollView>
    )
};

I can navigate fine if I'm selecting a different page (If I'm on the "Search Location" page and I want to go to the "Sign In" page everything works as expected). However, if I'm on the "Search Locations" page and I click on the "Search Locations" menu item, I want to simply close the drawer. I also want to tint the active page's icon/label. My problem is, from inside the DrawerMenu.js file, I don't know how to determine what page I'm currently on to do this.

Am I implementing this correctly? I'm new to React Native. Thanks in advance.

Upvotes: 2

Views: 2761

Answers (2)

Lenin Gonzalez
Lenin Gonzalez

Reputation: 194

for react navigation v5 you can use :

const DrawerMenu = (props) =>

const { state } = props
const { routes, index } = state; 
const focusedRoute = routes[index].name; // this is the active route

.....

Upvotes: 7

Jo Momma
Jo Momma

Reputation: 1307

I figured out a way to do it but I wonder if there is a better/simpler way than what I came up with. I added some hooks (useEffect, useState) and modified my navigateToScreen function. Here is my code. If it helps you out, upvote this. If you provided a better solution than mine, I will make it the accepted answer:

const DrawerMenu = (props) => {

    let activeIndex = props.navigation.state.index;
    let activeRouteName = props.navigation.state.routes[activeIndex].routeName;

    const [activeRoute, setActiveRoute] = useState('');

    useEffect(() => {
        setActiveRoute(activeRouteName);
    }, [activeRouteName, activeRoute]);


    const navigateToScreen = (route) => () => {

        if (activeRouteName === route){
            return props.navigation.closeDrawer();
        }

        const navAction = NavigationActions.navigate({
            routeName: route
        });

        props.navigation.dispatch(navAction);
    };

    return (
        <ScrollView style={styles.root}>

            <View style={styles.rowContainer}>
                <TouchableOpacity
                    onPress={navigateToScreen('Search Locations')}>
                    <View style={styles.row}>
                        <MaterialIcons
                            name='location-searching'
                            style={activeRouteName === "Search Locations" ? styles.activeIcon : styles.icon}
                            size={30}
                        />
                        <Text style={activeRouteName === "Search Locations" ? styles.activeLabel : styles.label}>
                            Search Locations
                        </Text>
                    </View>
                </TouchableOpacity>
            </View>

            <View style={styles.rowContainer}>
                <TouchableOpacity onPress={navigateToScreen('About')}>
                    <View style={styles.row}>
                        <MaterialIcons
                            name='info-outline'
                            style={activeRouteName === "About" ? styles.activeIcon : styles.icon}
                            size={30}
                        />
                        <Text style={activeRouteName === "About" ? styles.activeLabel : styles.label}>
                            About
                        </Text>
                    </View>
                </TouchableOpacity>
            </View>

            <View style={styles.rowContainer}>
                <TouchableOpacity onPress={navigateToScreen('Favorites')}>
                    <View style={styles.row}>
                        <MaterialIcons
                            name='favorite-border'
                            style={activeRouteName === "Favorites" ? styles.activeIcon : styles.icon}
                            size={30}
                        />
                        <Text style={activeRouteName === "Favorites" ? styles.activeLabel : styles.label}>
                            Favorites
                        </Text>
                    </View>
                </TouchableOpacity>
            </View>

            <View style={styles.rowContainer}>
                <TouchableOpacity onPress={navigateToScreen('Profile')}>
                    <View style={styles.row}>
                        <MaterialIcons
                            name='person-outline'
                            style={activeRouteName === "Profile" ? styles.activeIcon : styles.icon}
                            size={32}
                        />
                        <Text style={activeRouteName === "Profile" ? styles.activeLabel : styles.label}>
                            User Profile
                        </Text>
                    </View>
                </TouchableOpacity>
            </View> 
        </ScrollView>
    )
};

const styles = StyleSheet.create({
    root: {
        marginTop: 20,
    },
    row: {
        flexDirection: 'row',
        paddingTop: 16,
        paddingBottom: 16,
        alignItems: 'center',
        justifyContent: 'flex-start'
    },
    icon: {
        marginRight: 25,
        color: '#fff',
        padding: 2,
    },
    activeIcon: {
        marginRight: 25,
        color: colors.accent,
        padding: 2,
    },
    label: {
        fontSize: 20,
        color: '#fff',
    },
    activeLabel: {
        fontSize: 20,
        color: colors.accent,
    },
    rowContainer: {
        marginHorizontal: 16,
    }

});

export default DrawerMenu;

Upvotes: 0

Related Questions