i am using #react-navigation/stack^5.14.4 and #react-navigation/native^5.9.4, to handle the scene transition between Home, Login and Profile pages.
there are 2 transition cases i need to handle:
Home -> Profile (should have animation enabled)
Login -> Profile (need to skip the animation)
the reason why to skip the animation is that I am using a loading skeleton similar to the layout of Profile page during the login process. It is weird to have a transition between the profile page content and the skeleton itself. However I want to keep the awesome animation if pushed from Home page.
Is there a simple solution like
navigation.replace("Profile"); // with animation
navigation.replace("Profile", { animationEnabled: false }); // skip animation
You can use options to get the route property and check weather there is any parameter to disable the screen
snak: https://snack.expo.dev/#ashwith00/react-navigation-5-boilerplate
heres is an example
function TestScreen({ navigation }) {
return (
<View style={styles.content}>
<Button
mode="contained"
onPress={() => navigation.push('Test1', {disabledAnimation: true})}
style={styles.button}>
Push screen Without Animation
</Button>
<Button
mode="contained"
onPress={() => navigation.push('Test1')}
style={styles.button}>
Push new screen
</Button>
{navigation.canGoBack() ? (
<Button
mode="outlined"
onPress={() => navigation.pop()}
style={styles.button}>
Go back
</Button>
) : null}
</View>
);
}
const Stack = createStackNavigator();
function MyStack() {
return (
<Stack.Navigator>
<Stack.Screen
name="Test"
component={TestScreen}
options={{ title: 'Custom animation' }}
/>
<Stack.Screen
name="Test1"
component={TestScreen}
options={({ route }) => ({
title: 'Custom animation',
cardStyleInterpolator: !route.params?.disabledAnimation
? undefined
: CardStyleInterpolators.forNoAnimation,
})}
/>
</Stack.Navigator>
);
}
i find a more simple way to make it:
firstly, export the Stack.Screen node from the router file.
export const ProfileStack = (
<Stack.Screen name={'Profile'} component={Profile} />
);
export default Router = () => (
<Stack.Navigator>
<Stack.Screen name={'Home'} component={Home} />
<Stack.Screen name={'Login'} component={Login} />
{ProfileStack}
</Stack.Navigator>
);
then I can execute like this to disable the animation once.
with animation:
<Button onClick={() => {
navigation.replace('Profile');
}} />
without animation
<Button onClick={() => {
ProfileStack.props.options.animationEnabled = false;
navigation.replace('Profile');
ProfileStack.props.options.animationEnabled = true;
}} />
Related
Lets say I am in the tab - ChatStack and I am on the screen stack - AllChatRooms. Then when I click on one of the chat rows, I am then navigated to the chat room. I have it coded that, when in the ChatRoom screen, don't display nav bar and that works. But the ChatRoom screen does not reach full height and it acts like the nav bar is still there. I attached an image with colors so you can see what I am talking about.
Would really appreciate some help if anyone knows how to get the screen to reach the bottom of the phone screen.
So I am using a bottom tab navigator like this (simplified version):
Tabs.js
const getRouteName = (route) => {
const routeName = getFocusedRouteNameFromRoute(route);
if (routeName?.includes("HomeAllCategories") || routeName === "ChatRoom") {
return "none";
}
return "flex";
}
return (
<Tab.Navigator screenOptions={{ tabBarShowLabel: false }}>
<Tab.Screen name="Home" component={HomeStack}/>
<Tab.Screen name="Bookmarks" component={BookmarkStack}/>
<Tab.Screen name="Chats" component={ChatStack} options={({route}) => ({
tabBarStyle: {display: getRouteName(route)},
})}/>
<Tab.Screen name="Settings" component={SettingsStack}/>
</Tab.Navigator>
)
ChatStack.js
<Stack.Navigator>
<Stack.Screen name="AllChatRooms" component={AllChatRooms} />
<Stack.Screen name="ChatRoom" component={ChatRoom} />
</Stack.Navigator>
ChatRoom.js
return (
<SafeAreaView className="flex-1 bg-slate-900">
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : "height"}
className="flex-1"
keyboardVerticalOffset={10}
>
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<FlatList
data={messages}
className="pl-4"
keyExtractor={item => item.id}
renderItem={({ item }) =>
item.from === user.name ? (
<ReceiverMessage message={item} />
) : (
<SenderMessage message={item} />
)
}
/>
</TouchableWithoutFeedback>
{/* Text Box */}
<View className="bg-white flex-row justify-between items-center border border-gray-200 px-5 py-2">
<TextInput
className="h-10 text-lg w-4/5"
placeholder="Send Message..."
/>
<Button title="Send" color="#6ECCAF"/>
</View>
</KeyboardAvoidingView>
</SafeAreaView>
)
and I'm using:
"#react-navigation/bottom-tabs": "^6.5.2",
"#react-navigation/native": "^6.1.1",
"#react-navigation/native-stack": "^6.9.7",
But sometimes it does have the full height and I don't know why? On launch, the height of the screen is never working but after leaving and opening the chat room several times, the height of the screen does reach the bottom. Why is that?
I wanted to connect the SearchMain, SearchHistoryList, and SearchResult screens using the custom header of the stack navigation.
At first, the SearchMain screen appeared,
and when the TextInput in the custom header is onFocus, the SearchHistory screen appeared,
and the SearchResult screen appeared when the TextInput is onSubmitEditing or when the SearchButton was pressed.
Also, I set the keyboard focus to be maintained when switching screens, and use Keyboard.discuss() when I want to close it.
However, if you enter something at the TextInput in custom header immediately after the screen changes, it will be entered at the TextInput on the previous screen.
I think it's because the three screens don't share a single custom header!! each header is created, and the keyboard focus on the previous screen!!
I want all screens use the same header, or the values of the headers are consistent.
What should I do to solve this problem?
I searched variously such as singleton header, static header, and header value consistent, but there is no good solution.
I recently started studying React Native, so I'm not sure about my method, and a completely different approach is also welcome~~
Below is my code, thanks.
const Stack = createStackNavigator();
function NavigationBar({navigation}){
const [query, setQuery] = React.useState('');
function changeSearchQuery(text : string) : void {
setQuery(text);
}
function deleteSearchQuery() : void {
setQuery("");
}
return(
<InputView>
<BackIcon onPress={() => {navigation.goBack()
Keyboard.dismiss()}}>
<Icon name="arrow-back-ios" size={widthPercentage(24)} color="#666666"/>
</BackIcon>
<InputText
keyboardType="default"
maxLength={100}
onChangeText={(str) => setQuery(str)}
value = {query}
placeholder="검색어 입력"
placeholderTextColor="#E9E9E9"
returnKeyType="search"
onFocus={() => navigation.navigate("SearchHistory", {changeSearchQuery:changeSearchQuery})}
onSubmitEditing={() => {navigation.navigate("SearchResult", {changeSearchQuery:changeSearchQuery})
Keyboard.dismiss()}}
allowFontScaling= {false}
/>
{ query.length > 0 &&
<DeleteIcon onPress={() => deleteSearchQuery()}>
<Icon name="clear" size={widthPercentage(20)} color="#666666"/>
</DeleteIcon>
}
<SearchIcon onPress={() => {navigation.navigate("SearchResult")
Keyboard.dismiss()}}>
<Icon name="search" size={widthPercentage(20)} color="#666666"/>
</SearchIcon>
<Line></Line>
</InputView>
);
}
export const Search = () =>{
return (
<Stack.Navigator initialRouteName="SearchMain" keyboardHandlingEnabled={false} screenOptions={{header:props => <NavigationBar navigation={props.navigation}/>}}>
<Stack.Screen name="SearchMain" component={SearchMain} options={{animationEnabled: false}}/>
<Stack.Screen name="SearchHistory" component={SearchHistory} options={{animationEnabled: false}}/>
<Stack.Screen name="SearchResult" component={SearchResult} options={{animationEnabled: false}}/>
<Stack.Screen name="SearchFilter" component={SearchFilter} options={{headerShown: false}}/>
</Stack.Navigator>
);
}
export default Search;
It's not a good pattern to set the state inside the header, instead you should centralized the state in your component and then use navigation.setOption to pass functions/state value.
In this way your header will look like this:
function NavigationBar({
query,
onFocus,
onChangeText,
onPressBackIcon,
onSubmitEditing,
onDeleteSearch,
onSearch
}){
return(
<InputView>
<BackIcon onPress={onPressBackIcon}>
<Icon name="arrow-back-ios" size={widthPercentage(24)} color="#666666"/>
</BackIcon>
<InputText
keyboardType="default"
maxLength={100}
onChangeText={onChangeText}
value = {query}
placeholder="검색어 입력"
placeholderTextColor="#E9E9E9"
returnKeyType="search"
onFocus={onFocus}
onSubmitEditing={onSubmitEditing}
allowFontScaling= {false}
/>
{ query.length > 0 &&
<DeleteIcon onPress={onDeleteSearch}>
<Icon name="clear" size={widthPercentage(20)} color="#666666"/>
</DeleteIcon>
}
<SearchIcon onPress={onSearch}>
<Icon name="search" size={widthPercentage(20)} color="#666666"/>
</SearchIcon>
<Line></Line>
</InputView>
);
}
Than you will have in SearchMainScreen your state, your functions and your custom header:
// remember headerMode='none' in screen option
const SearchMainScreen = () => {
const [query, setQuery] = React.useState('');
const onFocus = () => {}
...
return (
<View>
<NavigationBar
onFocus={onFocus}
query={query}
...
/>
{
(isFocus && !query) ?
<SearchHistoryComponent/> :
(isFocus && query) ?
<SearchResultComponent/> :
<List/>
}
</View>
)
}
I am having a issue when I am nesting my Tabs within my Drawer. Unfortunately, navigating to each tab is very slow, and their seems to be a lot of lag.
However, when I remove the Drawer navigator, and make it so that their is only a tab navigator, navigating between the different tab screens is noticeably better.
How can I make it so that their is no delay between the tabs when the tabs are nested in to the drawer?
{ *
With help from Mateusz, I have managed to pinpoint the issue. I tested the delay by rendering four of the same components. The first test was using
children={() => {
return <NfcWifiConfig />;
}}
And the delay was still there
But then, when I used
component={NfcWifiConfig}
The delay is completely gone and navigation is running smoothly as it should. So my question now is, where do i go from here? How would i pass the props down with this syntax?
}
My current code is:
const DrawerComponent = ({
Bunch of props here
}) => {
return (
<Drawer.Navigator
drawerType="back"
drawerContent={(props) => {
return (
<DrawerContent
{...props}
/>
);
}}
>
{/* TABS */}
<Drawer.Screen
name="MainHome"
children={({navigation}) => {
return (
<>
<StatusBar backgroundColor={homeColor} barStyle="dark-content" />
<Navbar navigation={navigation} userimage={userimage} />
<Tabs.Navigator>
{/* HOME STACK */}
<Tabs.Screen
name="Profile"
children={() => {
return (
<>
<MainStackNavigator
{Bunch of props here}
/>
</>
;
}}
/>
{/* SEARCH SCREEN */}
<Tabs.Screen
name="Search"
children={() => {
return (
<>
<StatusBar barStyle="dark-content" />
<SearchStack
{ Bunch of props here }
/>
</>
);
}}
/>
{/* NFC-SOCIAL SCREEN */}
<Tabs.Screen name="Activate" component={NfcConfig} />
{/* NFC-WIFI SCREEN */}
<Tabs.Screen name="WiFi" component={NfcWifiConfig} />
</Tabs.Navigator>
</>
);
}}
/>
{/* Add Links Screen */}
<Drawer.Screen
name="Add Links"
children={({navigation}) => {
return (
<AddLinksScreen
{ Bunch of props here }
/>
);
}}
/>
{/* Following Screen */}
<Drawer.Screen
name="Followers"
children={({navigation}) => {
return (
<FollowerStack
{ Bunch of props here }
/>
);
}}
/>
{/* Following Screen */}
<Drawer.Screen
name="Following"
children={({navigation}) => {
return (
<FollowingStack
{ Bunch of props here }
/>
);
}}
/>
</Drawer.Navigator>
);
};
Also, the add links screen and followers/following screens work fine. Navigating to them works efficiently with no lag. But the tabs => home stack, search screen and the other two, have a heavy delay when navigating between them.
In terms of the content inside the tabs, the last two tabs are very light, and do not contain much content. I have tried commenting out the heavy tab screens and using just the two lightweight components, but same result. Making me believe that is not the issue.
So I managed to fix the issue. When I used:
children={() => {
return <NfcWifiConfig props{props} />;
}}
The lag was present. However, when I used:
component={NfcWifiConfig}
The lag disappeared. However, my props were not being passed through. So what I did was use React Context to pass my props to all the different components that needed it and that's it, the lag was gone and the components were receiving the props as I wanted.
Also, the code is a lot cleaner when using React context, so I highly recommend it.
The bottom tabs navigation is looking something like that:
const Tab = createBottomTabNavigator();
export default function TabStackScreen() {
return (
<Tab.Navigator initialRouteName="Home">
<Tab.Screen name="Home" component={HomeStackScreen} />
<Tab.Screen name="Favorites" component={FavoritesStackScreen} />
<Tab.Screen name="Search" component={SearchStackScreen} />
</Tab.Navigator>
)
}
There is not back button on the favorites and search screen. I guess this is the normal behavior, but I would love to have one.
I did not find something relevant in the doc, except recreating a component that looks like the native back button and adding it on some screens using headerLeft. Is there a more simple method?
In my projects I like to create custom headers, and I do not show the default header and show my own custom header component.
On my custom component I add right and left components, and let the screens decide what to do, by default the back button is shown, but if the screen pass the noBack property, the button is hidden.
You can also add a right component, for example a close button.
That is what I use to do:
const screenOptions = {
headerShown: false
};
<RootStack.Navigator screenOptions={screenOptions} mode="modal">
and then create my own component
export const Header = ({ title, leftComponent, rightComponent, noBack }) => {
const navigation = useNavigation();
return (
<Wrapper>
{leftComponent ||
(noBack ? (
<Placeholder />
) : (
<Button
onPress={() => navigation.goBack()}
accessible
accessibilityRole="button"
accessibilityLabel="Back">
<Icon
size={30}
name={Platform.OS === 'android' ? 'arrow-left' : 'chevron-left'}
/>
</Button>
))}
<Title bold accessibilityRole="header" acessible acessibilityText={title}>
{title}
</Title>
{rightComponent || <Placeholder />}
</Wrapper>
);
};
Doing that, you are able to customize everything on your header, it works like a charm for me.
I am new to react native and its navigation modules. I have a simple dashboard.js file where I am using tab navigator like this -
<Tabs.Navigator tabBarOptions={{ activeTintColor: '#ff5757' }}>
<Tabs.Screen
options={{
tabBarIcon: ({ color }) =>
<Icon name='star-border' size={30} padding={15} color={color} />,}}
name={'Orders'}
component={Order}
initialParams={{user}}
/>
<Tabs.Screen
component= {AnotherComponent}
/>
As you can see I am passing InitialParams where I have user props. And I can easily get it in Order component by route.params.
However, in my dashboard component I also have a method that runs every 1 minute and updates user props.
I can't get the updated value of user props in Order component. I am stuck with this for 2 days. In the past I have done like this -
<Tabs.Screen
component = {() => <SomeComponent props= {props}/>}
And it worked fine. But with react-navigation 5 its not working any more.
Please help me if anyone knows. plz.
Thanks a lot.
The initial props seems to be a constant also as per the documentation you have to use redux or context api to update the badge counts in the tabs so I think it will be better to take that approach to handle this problem. Came up with a count changing scenario just like yours using context API.
const CountContext = React.createContext(0);
function HomeScreen() {
return (
<View>
<CountContext.Consumer>
{value => <Text>Home! {value}</Text>}
</CountContext.Consumer>
</View>
);
}
const MyTabs = () => {
const [count, setCount] = React.useState(0);
return (
<CountContext.Provider value={count}>
<View style={{ flex: 1 }}>
<Text>{count}</Text>
<Button title="count" onPress={() => setCount(count + 1)} />
<Tab.Navigator>
<Tab.Screen name="Home" component={HomeScreen} options={{ title: 'My home' }} />
<Tab.Screen name="Settings" component={SettingsScreen} options={{ title: 'My home 2' }} />
</Tab.Navigator>
</View>
</CountContext.Provider>
);
};
This way you can skip the navigation params and directly send data to the tab, and this data can be read from other tabs or somewhere down the tree as well.
You can check the full snack here
https://snack.expo.io/#guruparan/5c2b97