React Navigation change Tab order programmatically - reactjs

I'm creating an app with react-native with using react-navigation for routing. I know we can change tab order in react-navigation initially. But in my case, I need to change tab order programmatically. Is there any way to do that?

The following is an "almost pseudo code" example. It should at least drive you in the right direction. The trick is to use a "connected" main navigation component which reacts to changes in a redux store (in my case I stored the tabs order in a "settings" reducer) and force re-render of the tabs and their order, changing the screenProps property passed down by react-navigation to each navigator. Then there is a TabSelector component which returns the correct screen based on the props passed. I'm sorry if it's not totally clear what I mean but English is not my primary language :)
import Tab1 from 'app/components/Tab1';
import Tab2 from 'app/components/Tab2';
// ... all the imports for react-navigation
const TabSelector = (props) => {
switch(props.tab) {
case 1:
return <Tab1 {...props} />;
case 2:
return <Tab2 {...props} />;
}
};
const Tabs = {
PreferredTab: {
screen: ({ screenProps }) => (
<TabSelector tab={screenProps.firstTab} />
),
navigationOptions: ({ screenProps }) => ({
// write label and icon based on screenProps.firstTab
})
},
OtherTab: {
screen: ({ screenProps }) => (
<TabSelector tab={screenProps.otherTab} />
),
navigationOptions: ({ screenProps }) => ({
// write label and icon based on screenProps.otherTab
})
},
// other tabs...
};
const Navigator = createTabNavigator(Tabs, {
initialRouteName: 'PreferredTab',
// other options...
});
const WrappedNavigator = props => {
// fetch tab index from redux state, for example
const firstTab = useSelector(state => state.settings.firstTab);
const otherTab = useSelector(state => state.settings.otherTab);
return <Navigator screenProps={{ firstTab: firstTab, otherTab: otherTab }} {...props} />;
};
WrappedNavigator.router = Navigator.router;
export default createAppContainer(WrappedNavigator);

Related

How to Change Header Title Component in React navigation

I am Using Product Search Component In Header Of EmptyPage , It works Fine . Now My Req is to change the Header Title Component Dynamically , If i come From DiagnosticSearch Page I need The Header Title Component Should Be , How to change it Dynamically???
<Stack.Screen name='EmptyPage' component={EmptyPage} options={{ headerShown:true,headerTitle: () => <ProductSearch/>}}/>
I would do it in the EmptyPage screen component,
create:
export const screenOptions = navData => {
const title = navData.route ? navData.route.params : null
return {
headerTitle: title,
}
and inside the function of EmptyPage
useEffect(() => {
props.navigation.setParams({ title:theUpdatedTitle })
}, [theUpdatedTitle])
now in the navigation :
<Stack.Screen name='EmptyPage' component={EmptyPage} options{importedScreenOptions}/>
hope this helps you

How to share a single MUI useScrollTrigger return value among multiple components?

I am currently using MUI's useScrollTrigger hook to determine the appearance of three components - NavBar, a post FAB a back to top button e.g.:
export default function NavBar() {
const isScrolledDown = useScrollTrigger({ target: window, threshold: 100 });
return (
<>
<Slide in={!isScrolledDown} >
<AppBar>
<Toolbar>
</Toolbar>
</AppBar>
</Slide>
<Toolbar />
<BackToTopFAB isScrolledDown={isScrolledDown} />
<PostCreateFAB isScrolledDown={isScrolledDown} />
</>
);
}
Since I do not want to make the browser listen for three separate "scroll" events, I am currently drilling the hook's return value from the NavBar into the two buttons.
However, as a result, I am unable to decouple the two buttons from the NavBar.
Does anyone have any suggestions how this may be possible, so that all three components share the same hook return value? If having multiple "scroll" listeners is not DOM-intensive, I am also willing to consider that
React hook is designed to be reusable, you probably want to move the useScrollTrigger hook to the components that need it like below:
const useCustomScrollTrigger = () => useScrollTrigger({ target: window, threshold: 100 });
const BackToTopFAB = () => {
const isScrolledDown = useCustomScrollTrigger();
return (...)
}
const PostCreateFAB = () => {
const isScrolledDown = useCustomScrollTrigger();
return (...)
}
const MyAppBar = () => {
const isScrolledDown = useCustomScrollTrigger();
return (
<Slide in={!isScrolledDown} >
<AppBar />
</Slide>
)
}
export default function NavBar() {
return (
<>
<MyAppBar />
<OtherContent />
<BackToTopFAB />
<PostCreateFAB />
</>
);
}
Doing so has a couple of advantages:
Your code is easier to read because the logic is hidden away in each specific component. Code readability is one of the most important factors when choosing between trade-offs IMO. Several additional event listeners should never impact your application performance in any way.
Improve your the performance of the parent component since there is no props at the top-level component, if the isScrolledDown state is changed, only 3 isolated components are re-rendered as a result. Otherwise, other components in the page like OtherContent also need to be rendered because the state in the parent component changes.
You can also have a look at some react state management libraries like redux-toolkit if you want to store the state in a single place and access it anywhere in the components regardless of its position in the hierarchy:
import { createSlice } from '#reduxjs/toolkit'
const { actions } = createSlice({
name: 'globalState',
initialState: { isScrolledDown: false },
reducers: {
setIsScrolledDown: (state, action) => {
state.isScrolledDown = action.payload
},
},
})
const ScrollLisenter = () => {
const isScrolledDown = useScrollTrigger({ /* ... */ });
const dispatch = useDispatch()
useEffect(() => {
dispatch(actions.setIsScrolledDown(isScrolledDown));
}, [isScrolledDown]);
return null
}
const BackToTopFAB = () => {
const isScrolledDown = useSelector(state => state.globalState.isScrolledDown);
return (...)
}
const PostCreateFAB = () => {
const isScrolledDown = useSelector(state => state.globalState.isScrolledDown);
return (...)
}
<App>
<ScrollLisenter />
<NavBar />
</App>
Related Question
Does adding too many event listeners affect performance?

React Navigation 6 Hide Drawer Item

How can I hide screens from appearing as items in the drawer of #react-navigation/drawer version 6.
In React Navigation 5 it was achieved by creating custom drawer content like this
const CustomDrawerContent = (props: DrawerContentComponentProps) => {
const { state, ...rest } = props;
const includeNames = ["ScreenOne", "ScreenTwo"];
const newState = { ...state }; //copy from state before applying any filter. do not change original state
newState.routes = newState.routes.filter(
(item) => includeNames.indexOf(item.name) !== -1
);
return (
<DrawerContentScrollView {...props}>
<DrawerItemList state={newState} {...rest} />
</DrawerContentScrollView>
);
};
As was described in this other answer. I have just upgraded to react-navigation 6 and with this technique I get an error TypeError: Cannot read property 'key' of undefined when I try to navigate one of these hidden screen. Can anyone help me out?
Update - Solution Found
I found a solution by myself so will put it here for anyone else looking. Set the drawer item style display hidden like this:
<DrawerStack.Screen
name="ScreenName"
component={ScreenComponent}
options={{
drawerItemStyle: {
display: "none",
},
}}
/>

Hiding specific tabs on react navigation bottomTabBarNavigation

Imagine I have this structure for my tab bar:
const TabBarRoute = {
Home: HomeStack,
Orders: OrdersStack,
Trending: TrendingStack,
TopSelling: TopSellingStack
}
I want to show only three tabs (Orders, Trending, TopSelling) in my bottom tab navigator, How can I achieve it by react-navigation version 3.x ?
One idea that come to my mind is that I create a top stackNavigator and nest HomeStack along with my bottomTabNavigator inside of that and set the initial route of the top stackNavigator to the Home but problem with this approach is that it doesn't show the tab bar.
This example is using createBottomTabNavigator, but I imagine the same rules apply. It requires overriding the tabBarButtonComponent with a Custom component which returns null when the user doesn't have access to the given Tab.
const Config = {
allow_locations: true,
allow_stations: true
}
LocationsStackNavigator.navigationOptions = ({navigation}) => {
return {
tabBarLabel: 'Locations',
tabBarTestID: 'locations',
tabBarIcon: ({focused}) => (
<TabBarIcon
focused={focused}
name={'md-settings'}/>
)
}
};
const MyTabNav = createBottomTabNavigator(
{
LocationStackNavigator,
StationsStackNavigator,
OrdersStackNavigator,
SettingsStackNavigator
},
{
defaultNavigationOptions: ({ navigation }) => ({
tabBarButtonComponent: CustomTabButton
})
}
);
class CustomTabButton extends React.Component {
render() {
const {
onPress,
onLongPress,
testID,
accessibilityLabel,
...props
} = this.props;
if(testID === 'locations' && !Config.allow_locations) return null;
if(testID === 'stations' && !Config.allow_stations) return null;
return <TouchableWithoutFeedback onPress={onPress} onLongPress={onLongPress} testID={testID} hitSlop={{ left: 15, right: 15, top: 5, bottom: 5 }} accessibilityLabel={accessibilityLabel}>
<View {...props} />
</TouchableWithoutFeedback>;
}
}
if you want to have dynamic items which they can change according to your situation you can do it in 2 ways :
first, you can declare a component as a parent of your react-navigation component then
create a store for your items and set them as #observable and change them whenever you want
declare your items as a state of your parent component and pass them to your react navigation
In these two solutions, every time your items change caused your component re-render with new values

Custom back navigation for reactnavigation back button

How can I give a custom navigation to the header back arrow in ReactNavigation? I want the back arrow in the header to navigate to the screen I define and not to the previous screen.
Thanks.
You could try 2 things:
a) use headerMode: 'none' in your sub-StackRouters instead of your root router (named RouterComponent). Ideally you shouldn't have to do anything more then and the headers of the sub-StackRouters would be displayed in your root router's header. I think I remember something similarly worked a while back for me, but I haven't tested it in a while now and I think it's unlikely that it will still work like this but you can test nevertheless.
b) and this is what I'm currently using in a different situation. To manually include the back button:
import { HeaderBackButton } from '#react-navigation/stack';
const navigationOptions = ({ navigation }) => ({
headerLeft: <HeaderBackButton onPress={() => navigation.goBack(null)} />,
})
const RouterComponent = StackNavigator({
Tabs: {
screen: Tabs
},
Profile: {
screen: ProfileStack,
navigationOptions
}
},{
mode: 'modal',
headerMode: 'none',
});
If above solution doesn't work,
Try to add navigationOptions directly to the ProfileStack definition.
const ProfileStack = StackNavigator({
ProfileHome: {
screen: ProfileHome,
navigationOptions: ({navigation}) => ({ //don't forget parentheses around the object notation
title: 'Profile',
headerLeft: <HeaderBackButton onPress={() => navigation.goBack(null)} />
})
},
ProfileEdit: { screen: ProfileEdit }
}
Hi who ever is using react-navigation 5.x you might not be able to make navigation using navigationOptions. The option is been replaced with options.
Say your in screen -1 and navigated to screen-2 and then to screen-3. By default using react-navigation you can navigate from screen-3 to screen-2. But if you want customised navigation i.e., Say from above example if you want to navigate from screen-3 to screen-1.
If you would like to retain the view of back button and only override the onPress method, you can import { HeaderBackButton } from '#react-navigation/stack' and assign that component to the headerLeft option.
Example:
<RootStack.Screen
name="dashboard"
component={Dashboard}
options={({navigation, route}) => ({
headerLeft: (props) => (
<HeaderBackButton
{...props}
onPress={() => navigation.navigate('Home')}
/>
),
})}
/>
In above example on click of back button in Dashboard screen takes you to Home screen.
Enjoy & Thanks
-Sukshith

Resources