React Native and React Native Navigation - Handle Back (goBack) issue - react-native

thank you for taking time to read & answer this question. I'll give my best to explain the issue I'm having.
The HomeStack component holds bottom navigation for four screens. One screen that is giving me a headache is ProjectsStack
export const ProjectsStack = (): ReactElement => {
return (
<ProjectsStackNav.Navigator initialRouteName='ProjectsScreen' screenOptions={defaultScreenOptions}>
<ProjectsStackNav.Screen name='ProjectsScreen' component={ProjectsScreen} />
<ProjectsStackNav.Screen name='CompletedProjectsScreen' component={CompletedProjectsScreen} />
<ProjectsStackNav.Screen name='ProjectTasksScreen' component={ProjectTasksScreen} />
<ProjectsStackNav.Screen name='CompletedProjectsTasksScreen' component={ProjectTasksScreen} />
</ProjectsStackNav.Navigator>
);
};
As you can see the ProjectTasksScreen is a component that renders a project based on the props => if it's open it will render ProjectTasksScreen otherwise it will render CompletedProjectsTasksScreen which is basically the same screen (reusability at its finest lol)
In order to go to the CompletedProjectsTasksScreen, you need to come from ProjectTasksScreen.
Now, the issue is when you want to go back from CompletedProjectsTasksScreen it will not go to ProjectTasksScreen, rather it will navigate to the previous screen of ProjectTasksScreen which is ProjectsScreen.
Is there a better solution to this problem than refactoring everything into it's screen & component?

navigation.push method instead of navigation.navigate may resolve your issue
https://reactnavigation.org/docs/navigating/#navigate-to-a-route-multiple-times

Related

How to determine mouse events in React Native (mobile)?

I need to use a callback function for the mouse click event. Below code is working in React web app:
const checkAnswer = (e: React.MouseEvent<HTMLButtonElement>) => {
const answer = e.currentTarget.value // here .value property is undefined and gives error in React-Native. Just e.currentTarget is defined.
const correct = questions[number].correct_answer === answer
if(correct) setScore(prev => prev + 1)
}
But I couldn't apply it on React Native (mobile) for Pressable or TouchableOpacity.
This is the render part of React web app's code:
<button value={answer} onClick{checkAnswer} />
and I try to apply it on React Native. The value will be passed to button's value. But there is no "value" option in native's Pressable component. Therefore I am confused
Any help?
you can determine touch events by following
<View onTouchStart={(e) => {console.log('touchMove',e.nativeEvent)}} />
Here is some similar scenario what I could able to understand from the question.
There is a Score state which will store the user's score of a quiz game.
There is a array of question where all the options and correct option are given.
There will be a button for the option, if user choose a option, and based on that it will validate if user is correct or not.
It might not be the exact scenario of you. But this could definitely help to solve your scenario.
Here is a solution for the scenario => solution.
If you click on the solution link you will be redirect to a page which is similar to the screenshot attached below. On very right you will find "My Device", "Android", "ios", choose any and run. Run via "my device" with expo app installed in your mobile if you don't want to be in queue for some certain time.
Note: from your code this is for React web:
<button value={answer} onClick{checkAnswer} />
but in React Native you have to use a click event like this:
<TouchableOpacity onPress={()=>buttonHandler()}></TouchableOpacity>
Here ()=> and () extra need to be added to work a function properly.
Also instead of .map() function you can use FlatList to improve your app. FlatList support lazy loading.

How to add a screen switcher component in react native

Being a newbie to the field of app development, I actually don't know the name of this UI component .
This component basically act as a switcher between two screen, which shows up Explore screen when Explore is clicked and My Community screen when My Community is clicked
Someone please help me to know what to call this component and which npm package need to be used to deploy it.
THANKS IN ADVANCE!!!
You can use the switch component and its boolean value to conditionally display different screens/components.
Basic example using setState:
const [isEnabled, setIsEnabled] = useState(false);
const toggleSwitch = () => setIsEnabled(previousState => !previousState);
return (
<View>
<Switch
onValueChange={toggleSwitch}
value={isEnabled}
/>
{isEnabled ? <Text>Placerholder Screen 1</Text> : <Text>Placerholder Screen 2</Text>}
</View>
);
But in this situation I would advise you to use Tabs instead of a Switch. React Navigation is a great library to help you with this. You may want to look at the bottom tabs, material bottom tabs or material top tabs.

How to goBack globally between stacks in React Navigation?

I am using react navigation ("#react-navigation/native": "^5.1.3") and I have the following setup:
BottomNavigation
-stack1
-stack2
It looks like goBack() is local to the stack. What that means is that if I navigate from a page in stack1 to a page in stack2, I am unable to go the the page I came up from.
Solutions (or rather hacks) that didn't work for me:
pass the source screen as param and then navigate. That isn't a real back button and does not play well with android back button.
Put all pages in bottom navigation. Bottom navigation does not have animations it seems, so I can not achieve the right transitions
Put all pages in stack navigation. In this case I lose the fixed bottom navigation. I can add it to each page, but when transitioning it will go away with the old screen and come again with the new one, which is undesirable.
So I am wondering if I am missing something big here, like a globalBack() that I overlooked?!
And also, I am looking for a solution to this problem which remains.
Naturally if you have bottoms tabs with each tab having its own stack navigator, calling navigation.goBack() will go back from one screen inside stack navigator to previous screen inside that same stack navigator. That's how navigation works in pretty much every app. Pressing back button or swiping back does not change tab for you, tabs are more like separate small apps by itself. If you want to specifically jump from one tab to another instead of going back in stack, use navigation.dispatch(TabActions.jumpTo('Profile')). If pressing something inside tab#1 makes you go to to tab#2 then this screen most likely also belongs to tab#1
also, take a look at backBehavior prop of Tab.Navigator, it might be doing what you want depending on what exactly it is you want https://reactnavigation.org/docs/bottom-tab-navigator/#backbehavior
I'm using bottom tab navigator with 2 stacks as well. I faced similar issue and agree with #Max explanation. Due to my Notification screen is in Stack 1, I have to goBack to Notification after navigating away to Detail screen. After searching for the fix, I'm using this workaround (for v6).
Tab 1 - Stack 1 (Home > Notification screen)
Tab 2 - Stack 2 (Reward Home > Reward Detail screen)
I passed a param when navigating from Notification to RewardDetail. Then I override the headerLeft and use BackHandler to handle Android back function.
Notification.js
navigation.navigate('RewardStack', {
screen: 'RewardDetail',
initial: false,
params:{notification: notification_data_source}
})
RewardDetail.js
const payload = route.params.notification
//1. override headerLeft button
useLayoutEffect(() => {
if(payload)
navigation.setOptions({
headerLeft: () => (
<Button
TouchableComponent={TouchableOpacity}
buttonStyle={{paddingTop:4, paddingLeft:0}}
type='clear'
icon={<Icon name={'chevron-left'} size={30} style={{color:'#FFF'}} />}
onPress={()=>{
navigation.goBack()
navigation.navigate('Notification') //can use this only
}}
/>
)
})
}, [navigation]);
//2. Add BackHandler
useEffect(() => {
const onBackPress = () => {
if (payload) {
navigation.goBack()
navigation.navigate('Notification') //can use this only
return true
} else {
return false
}
}
BackHandler.addEventListener('hardwareBackPress', onBackPress)
return () => BackHandler.removeEventListener('hardwareBackPress', onBackPress)
}, [navigation]);
I can just use navigation.navigate('Notification') to return to Notification but this will cause Detail screen to stay mounted in Stack 2. I want the Stack 2 to return to RewardHome after go back to Notification. Hence I used:
navigation.goBack() //pop screen to RewardHome
navigation.navigate('Notification') //jump to Notification

BottomNavigation in react native

I create a bottom navigation in my react native project. But its not looking good in Iphone10.
It showing extra space in bottom.Please help me how to resolve this.
This is below code i tried.
import BottomNavigation,{FullTab} from 'react-native-material-bottom-navigation'
<BottomNavigation
onTabPress={newTab => this.clickoftab(newTab.key)}
renderTab={this.renderTab}
tabs={this.tabs}
/>
My render tab part is this
renderTab = ({ tab, isActive }) => {
return (
<FullTab
style={{padding:0,margin:0}}
key={tab.key}
isActive={isActive}
label={tab.label}
renderIcon={this.renderIcon(tab.icon)}
/>
)
}
This is my output which i want to change in bottom navigation
Depending of your architecture app, if like you say in the comments, if you use SafeAreaView I thought in create the BottomNavigation at the same level of the SafeAreaView. I mean (sorry my english), I suppose that you have the SafeAreaView in your "Father file" like App.js. So, at the same time you can manage the BottomNavigation from there. So, you could put SafeAreaView inside of BottomNavigation making BottomNavigation the father of your app I guess. I don't know if I am explaining well. The conclusion could be that
just apply SafeArea To things that are inside of Navigation instead of
full application.

react native route flux re-render component on stack pop

How do you re-run React Component Lifecycle methods to determine if a re-render is necessary when transitioning back to previous screens from stack using React Native Router Flux?
Scenario: Scene A -> B -> A
Lets say, A is the initial scene and we navigate from A to B with a push i.e Actions.SceneB. From B to A with a Pop. When the stack is popped to show Scene-A, none of the React Component methods are called for Scene-A. How do I determine if a re-render is necessary? I searched the Issues listed on the github repo and many seems to have this problem without a solution. How is this problem addressed?
I have the ugly work around of calling Actions.refresh() with a setTimeout.
Work Around that works!
This workaround seems to be hacky. There must be a better way to hook into component lifecycle to determine if a re-render is required. Perhaps a callback into the Component?
<TouchableHighlight underlayColor='#efefef' onPress={() => { Actions.pop(); setTimeout(()=> Actions.refresh(), 500)}} style={styles.cancel}>
Options that do not work
Actions.pop({type: 'reset'})
OR
Actions.refresh({"key" : "sceneA"})
Work Around that works! This workaround seems to be hacky. There must be a better way to hook into component lifecycle to determine if a re-render is required.
<TouchableHighlight underlayColor='#efefef' onPress={() => { Actions.pop(); setTimeout(()=> Actions.refresh(), 500)}} style={styles.cancel}>
This will call shouldComponentUpdate() method which gives an option to determine, if a re-render is required.
I was facing the same issue below code gave me required result.
let count = 0;
moveToMainScreen = () => {
count += 1;
Actions.pop({ refresh: { test: count } });
};
<Button onPress={this.moveToMainScreen}> Click </Button>