metamorph_online
metamorph_online

Reputation: 204

custom drawer focused from @react-navigation/drawer is not working correctly

I'm building app that requires custom drawer elements. I want to be able to highlight currently selected screen. I use Context to keep the state of the current screen selected and it changes indeed. changeDrawerElem is the function that keeps element number in Contex and I see that it changes onPress in console.log. However, elements of the CustomDrawerContent are rendered all focused regardless my attempt to control them. In docs it is said the property "focused" should take boolean value and based on that highlight focused element. react navigation version: 5 Any help is appreciated.

import React, { Component } from 'react';
import { useContext } from 'react';
import { Context } from '../context/settingContext';
import { StyleSheet, Text, View, ImageBackground, TouchableOpacity} from 'react-native';
import { DrawerContentScrollView, DrawerItemList, DrawerItem } from '@react-navigation/drawer';
import FontAwesome, { SolidIcons, RegularIcons, BrandIcons } from 'react-native-fontawesome';
import defaultStyles from '../css/defaultStyles';

function CustomDrawerContent (props){

    const {state} = useContext(Context);
    const {drawerElem} = state.find(elem => elem.hasOwnProperty('drawerElem'));
    const {changeDrawerElem} = useContext(Context);


    return(
        <DrawerContentScrollView {...props}>
            <DrawerItem
                label="Головна"
                onPress={() => {
                    changeDrawerElem(1);
                    props.navigation.navigate('StackNav', { screen: 'MainScreen'} )
                }}
                icon={() => <FontAwesome style={styles.drawerIcons} icon={SolidIcons.home} size={30} />}
                inactiveTintColor = "#000000"
                activeBackgroundColor = "#cdb9a5"
                focused = { () => drawerElem == 1 ? true : false}
             />
             <DrawerItem
                label="Зміст"
                onPress={() => {
                    changeDrawerElem(2);
                    props.navigation.navigate('StackNav', { screen: 'Content' });
                }}
                icon={() => <FontAwesome style={styles.drawerIcons} icon={SolidIcons.listOl} size={30} />}
                inactiveTintColor = "#000000"
                activeBackgroundColor = "#cdb9a5"
                focused = { () => drawerElem == 2 ? true : false}
              />
              
        </DrawerContentScrollView>
    );
}

const styles = StyleSheet.create(defaultStyles);

export default CustomDrawerContent;

Upvotes: 1

Views: 1130

Answers (1)

Mohamed Ahmed
Mohamed Ahmed

Reputation: 347

I found an answer which solved my problem, you need to change your focused props to

focused={props.state.index ===  props.state.routes.findIndex(e => e.name === 'Головна')}

Upvotes: 3

Related Questions