Home > Mobile >  Set useRef between component for dynamic text in button
Set useRef between component for dynamic text in button

Time:11-05

I have a simple tab screen where i am using React Navigation. I want to change the tab button in the parent component from inside my child components but cannot find a good solution to how.

Any help is greatly appriciated.

import React, {useRef, useEffect, useState} from 'react';

// Tab child FriendsList
function FriendsList({navigation}) {
    // Content here like ajax calls etc.
}

// Tab child FriendsFind
function FriendsFind({navigation}) {
   // Content here like ajax calls etc.
}
    
// Tab parent
function FriendsHomeScreen({navigation}){
    const Tab = createBottomTabNavigator();
    // I would like to have this ref dynamic and change it from the child tabs FriendsList and FriendsFind
    const refFriendRequests = useRef(0);
    
    <View style={{flex:1}}>   
    
        <Tab.Navigator
        initialRouteName="FriendsList"
        screenOptions={{
            tabBarIconStyle: { display: 'none' },
            headerShown: false,
            backgroundColor:'#000',
            tabBarStyle: {
              // style here
            },
        }}> 
            <Tab.Screen
                name="FriendsList"
                component={FriendsList}
                options={{
                    tabBarLabel: 'Friends',                   
                }}
            />
            <Tab.Screen
                name="FriendsFind"
                component={FriendsFind}
                options={{
                    // I would like to have this ref dynamic and change it from the child tabs FriendsList and FriendsFind
                    tabBarLabel: 'Find friends (' refFriendRequests.current ')',
                }}
            />
        </Tab.Navigator>
    
    </View>
}

CodePudding user response:

just add a fuction in the parent that cange the ref then pass it to the children .

const changeRef= (newValue)=>{
refFriendRequests.current =id,

}

then pass it

<Tab.Screen
                name="FriendsList"
                children={()=>{<FriendsList changeRef = {changeRef}/>}}
                options={{
                    tabBarLabel: 'Friends',                   
                }}
            />

note i changed component to children so i can pass props like this answer How to pass props to Screen component with a tab navigator?

edit
i forget to say that you of course need to add the function as a parameter

function FriendsList({navigation ,changeRef}) {
    // Content here like ajax calls etc.
}

edit 2 this is the answer that worked for the one who asked the question (although it seems that i misunderstood the question )

<Tab.Screen 
   name="FriendsFind" 
   options={{ 
      tabBarLabel: 'Find friends (' countRequests ')', 
   }}> {(props) => (<FriendsFind updateCountRequests ={updateCountRequests} {...props}/>)} 
   </Tab.Screen>
  • Related