React component retains previous state - react-native

I've been learning React and React Native for less than a week, so there are concepts that I'm still learning.
The code below is a first attempt to code an app with navigation through a bottom tab navigator, more specifically using #react-navigation/material-bottom-tabs and react-native-paper. There are 3 screens called Home, Details and Help. Home and Details both contain a button "ask for help", which will both redirect to the Help screen with a special message that is passed as parameter. For example:
<Button
icon="camera"
mode="contained"
onPress={() => navigation.navigate("Help", { txt: "Everything is OK!" })}
style={{ marginTop: 16 }}
>
Ask for help
</Button>
When loading the application, HelpScreen is initiated with initialParams={{ txt: "nothing" }} and the screen will display You said nothing.
From HomeScreen, clicking on the button redirects me to HelpScreen with onPress={() => navigation.navigate("Help", { txt: "Everything is OK!" })}. Therefore the screen will display You said Everything is OK!.
When moving to another screen and then going back to HelpScreen with the use of the bottom tabs, I expect HelpScreen to be re-rendered with its original value. Therefore I expect the screen to say You said nothing. But no, it still says You said Everything is OK!. The same behavious happens with DetailsScreen with another text.
In the HelpScreen function, I am not saving the parameter to a state. So I don't expect the component to retain the previous value when re-rendering. So why doesn't the component reset to its original value when re-rendering?
Or is it not re-rendering? In which case can you please explain why?
Here is the code:
import { registerRootComponent } from "expo";
import { NavigationContainer } from "#react-navigation/native";
import { NativeStackScreenProps } from "#react-navigation/native-stack";
import { createMaterialBottomTabNavigator } from "#react-navigation/material-bottom-tabs";
import { View } from "react-native";
import { Button, Text } from "react-native-paper";
import { SafeAreaProvider } from "react-native-safe-area-context";
import MaterialCommunityIcons from "react-native-vector-icons/MaterialCommunityIcons";
type NavigationParamList = {
Home: undefined;
Details: undefined;
Help: { txt: string };
};
type PropsHome = NativeStackScreenProps<NavigationParamList, "Home">;
type PropsDetails = NativeStackScreenProps<NavigationParamList, "Details">;
type PropsHelp = NativeStackScreenProps<NavigationParamList, "Help">;
const Tab = createMaterialBottomTabNavigator<NavigationParamList>();
function HomeScreen({ navigation, route }: PropsHome) {
console.log("HOME");
return (
<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
<Text>Route name: {route.name}</Text>
<Button
icon="camera"
mode="contained"
onPress={() =>
navigation.navigate("Help", { txt: "Everything is OK!" })
}
style={{ marginTop: 16 }}
>
Ask for help
</Button>
</View>
);
}
function DetailsScreen({ navigation, route }: PropsDetails) {
console.log("DETAILS");
return (
<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
<Text>Route name: {route.name}</Text>
<Button
icon="camera"
mode="contained"
onPress={() => navigation.navigate("Help", { txt: "HELP ME!" })}
style={{ marginTop: 16 }}
>
Ask for help
</Button>
</View>
);
}
function HelpScreen({ route }: PropsHelp) {
console.log("HELP");
return (
<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
<Text>Route name: {route.name}</Text>
<Text>You said {route.params.txt}</Text>
</View>
);
}
export default function App() {
return (
<SafeAreaProvider>
<NavigationContainer>
<Tab.Navigator initialRouteName="Home" screenOptions={{}}>
<Tab.Screen
name="Home"
options={{
tabBarIcon: ({ color }) => (
<MaterialCommunityIcons name="home" color={color} size={26} />
),
}}
component={HomeScreen}
/>
<Tab.Screen
name="Details"
options={{
tabBarIcon: ({ color }) => (
<MaterialCommunityIcons
name="alien-outline"
color={color}
size={26}
/>
),
}}
component={DetailsScreen}
/>
<Tab.Screen
name="Help"
options={{
tabBarIcon: ({ color }) => (
<MaterialCommunityIcons
name="chat-question-outline"
color={color}
size={26}
/>
),
}}
component={HelpScreen}
initialParams={{ txt: "nothing" }}
/>
</Tab.Navigator>
</NavigationContainer>
</SafeAreaProvider>
);
}
registerRootComponent(App);
Note that I have not used the useState hook. I understand that this hook would be needed when one wants the retain a value, not reset it.

React Navigation avoids rerendering each screen every time is focused for both better user experience and avoiding unnecessary screen rerendering.
You should override this default behavior and detect when the screen is revisited/focuses and rerender that screen.
It provided utility hooks to listen to the screen is focused - https://reactnavigation.org/docs/function-after-focusing-screen/
Here code refactor with a solution:
import { registerRootComponent } from "expo";
import {useEffect,useState} from "react"
import { NavigationContainer ,useIsFocused} from "#react-navigation/native";
import { NativeStackScreenProps } from "#react-navigation/native-stack";
import { createMaterialBottomTabNavigator } from "#react-navigation/material-bottom-tabs";
import { View } from "react-native";
import { Button, Text } from "react-native-paper";
import { SafeAreaProvider } from "react-native-safe-area-context";
import MaterialCommunityIcons from "react-native-vector-icons/MaterialCommunityIcons";
type NavigationParamList = {
Home: undefined;
Details: undefined;
Help: { txt: string };
};
type PropsHome = NativeStackScreenProps<NavigationParamList, "Home">;
type PropsDetails = NativeStackScreenProps<NavigationParamList, "Details">;
type PropsHelp = NativeStackScreenProps<NavigationParamList, "Help">;
const Tab = createMaterialBottomTabNavigator();
function HomeScreen({ navigation, route }: PropsHome) {
console.log("HOME");
return (
<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
<Text>Route name: {route.name}</Text>
<Button
icon="camera"
mode="contained"
onPress={() =>
navigation.navigate("Help", { txt: "Everything is OK!" })
}
style={{ marginTop: 16 }}
>
Ask for help
</Button>
</View>
);
}
function DetailsScreen({ navigation, route }: PropsDetails) {
console.log("DETAILS");
return (
<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
<Text>Route name: {route.name}</Text>
<Button
icon="camera"
mode="contained"
onPress={() => navigation.navigate("Help", { txt: "HELP ME!" })}
style={{ marginTop: 16 }}
>
Ask for help
</Button>
</View>
);
}
function HelpScreen({ route ,navigation}: PropsHelp) {
const [message,setMessage] = useState("")
const isFocused = useIsFocused()
useEffect(()=>{
setMessage(route.params.txt)
return ()=>{
navigation.setParams({txt:"nothing"})
}
},[isFocused])
return (
<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
<Text>Route name: {route.name}</Text>
<Text>You said {message}</Text>
</View>
);
}
export default function App() {
return (
<SafeAreaProvider>
<NavigationContainer>
<Tab.Navigator initialRouteName="Home" screenOptions={{}}>
<Tab.Screen
name="Home"
options={{
tabBarIcon: ({ color }) => (
<MaterialCommunityIcons name="home" color={color} size={26} />
),
}}
component={HomeScreen}
/>
<Tab.Screen
name="Details"
options={{
tabBarIcon: ({ color }) => (
<MaterialCommunityIcons
name="alien-outline"
color={color}
size={26}
/>
),
}}
component={DetailsScreen}
/>
<Tab.Screen
name="Help"
options={{
tabBarIcon: ({ color }) => (
<MaterialCommunityIcons
name="chat-question-outline"
color={color}
size={26}
/>
),
}}
component={HelpScreen}
initialParams={{ txt: "nothing" }}
/>
</Tab.Navigator>
</NavigationContainer>
</SafeAreaProvider>
);
}
Working Demo - https://snack.expo.dev/#emmbyiringiro/493761

Related

React-Native Header Title and Tab Navigator

I’ve a problem I cannot find an answer to, even though I’ve found similar problems with answers.
Basically, I pull a name (and other info) from a database. I then navigate to a screen (Screen A) in a tab navigator. I place the name into the header title of that screen (needed a stack navigator to do that I discovered from this site). I then have a second tab (Screen B) I can navigate to and want that same name placed in the header title there.
While on Screen B I also need to change the name and have that placed back into the header title of both Screen A and Screen B.
How do I do this? I have example code below that hopefully explains in more detail.
App.js
import React from 'react';
import { Text, View } from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import { createBottomTabNavigator } from '#react-navigation/bottom-tabs';
import { HomeScreen, ScreenA, ScreenB } from './ui/screens.js';
const AStack = createStackNavigator();
function ScreenAStack(headerProps) {
return (
<AStack.Navigator>
<AStack.Screen name="Screen A" component={ScreenA} />
</AStack.Navigator>
);
}
const BStack = createStackNavigator();
function ScreenBStack(headerProps) {
return (
<BStack.Navigator>
<BStack.Screen name="Screen B" component={ScreenB} />
</BStack.Navigator>
);
}
const BottomTab = createBottomTabNavigator();
function Tabs() {
return (
<BottomTab.Navigator
screenOptions={{ headerShown: false }}
>
<BottomTab.Screen name="Screen A Stack" options={{ title: "Screen A" }}>
{(props) => (
<ScreenAStack {...props} />
)}
</BottomTab.Screen>
<BottomTab.Screen name="Screen B Stack" options={{ title: "Screen B" }}>
{(props) => (
<ScreenBStack {...props} />
)}
</BottomTab.Screen>
</BottomTab.Navigator>
);
}
const Stack = createStackNavigator();
const App = () => {
return (
<NavigationContainer>{
<Stack.Navigator>
<>
<Stack.Screen name="Home Screen" options={() => ({ headerShown: true })} component={HomeScreen} />
<Stack.Screen name="Screen A Tabs" options={() => ({ headerShown: false })} component={Tabs} />
</>
</Stack.Navigator>
}</NavigationContainer>
);
}
export default App;
screens.js
import React, { useEffect } from 'react';
import { View, Text, TextInput, StyleSheet, Button, } from 'react-native';
export function HomeScreen({ navigation }) {
// Get name from server using api and send to Screen A.
navList = (item) => {
navigation.navigate("Screen A Tabs", {
screen: 'Screen A Stack',
params: {
screen: 'Screen A',
params: { item },
},
});
}
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen.</Text>
<Button title="Go to Tab Screen" onPress={() => navList({name: "Name here!"})} />
</View>
);
}
export function ScreenA({ route, navigation }) {
// Place name into header title.
useEffect(() => {
navigation.setOptions({
title: route.params.item.name,
});
}, [route]);
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Screen A</Text>
</View>
);
}
export function ScreenB({ navigation }) {
// Update header title with new name and update name on server using api.
const [newName, setNewName] = React.useState("");
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Screen B</Text>
<TextInput
value={newName}
onChangeText={newName => setNewName(newName)}
placeholder="Type new name here."
/>
<Button title="Change Name" onPress={() => console.log("Change name to " + newName)} />
</View>
);
}
I will give a short answer. your do not need to create a separate stacks for a single screen. here you can create a simple bottom tab navigator. just a sample.
<Tab.Navigator
initialRouteName="SearchScreen"
backBehavior="initialRoute"
screenOptions={{headerShown: false}}
>
<Tab.Screen
name="SearchScreen"
component={SearchScreen}
options={{
headerShown: false,
tabBarLabel: 'Search',
tabBarIcon: 'search',
}}
/>
<Tab.Screen
name="DialerScreen"
component={DialerScreen}
options={{
headerShown: false,
tabBarLabel: 'Dialer',
tabBarIcon: 'dialer',
}}
/>
</Tab.Navigator>
after this create a simple stack and add this bottom or top tab navigator like this
<Stack.Screen
name="Home"
component={TopTabNavigator}
options={{headerShown:true}}
/>
you can change title like this
onPress={() => {
if (item.is_analog) {
navigation.setOptions({title: 'Analog Speedo Meter'});
} else {
navigation.setOptions({title: 'Digital Speedo Meter'});
}
}}
cheers

how to remove this white ovale behind the focused in the Material Bottom Tabs Navigator

Using #react-navigation/material-bottom-tabs
and following this doc
I wonder how can I remove this weird white round behind the active tab icon?
Its been 2hours I am trying everything. I am missing something
(nb: I am using the same code of the exemple in the doc, if you want to reproduce, with react-native 0.70.6, I had not this problem on the v 0.68.1 )
EDIT: also with shifting={true} when I click on the tab:
To "remove" the tab icon, we can set its color to transparent. However, there is no direct way to manipulate the tab icon's color within #react-navigation/material-bottom-tabs.
#react-navigation/material-bottom-tabs is a wrapper of BottomNavigation in react-native-paper. Thus, the issue is with react-native-paper. This SO question addresses the exact problem. We need to make changes to the theme, where the tab icon's color can be controlled.
However, according to the doc, theme from react-native-paper cannot be directly applied to react navigation. We have to use Provider from react-native-paper and apply the theme to the Provider.
See the sample code and effect below.
import * as React from 'react';
import {Text, View} from 'react-native';
import {
NavigationContainer,
useNavigationContainerRef,
} from '#react-navigation/native';
import {createMaterialBottomTabNavigator} from '#react-navigation/material-bottom-tabs';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import {DefaultTheme, Provider} from 'react-native-paper';
const Tab = createMaterialBottomTabNavigator();
function HomeScreen() {
return (
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<Text>Home!</Text>
</View>
);
}
function ProfileScreen() {
return (
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<Text>Profile!</Text>
</View>
);
}
function SettingsScreen() {
return (
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<Text>Settings!</Text>
</View>
);
}
const App = () => {
const barColors = {
home: 'aqua',
settings: 'gold',
profile: 'lawngreen',
};
const [tab, setTab] = React.useState<keyof typeof barColors>('home');
const navRef = useNavigationContainerRef();
React.useEffect(() => {
const unsubscribe = navRef.addListener('state', () => {
const currRoute = navRef.getCurrentRoute();
if (currRoute) {
// A work-around to set background color for the bar after the ripple
// effect completes. The 200 ms delay comes from trial and error
setTimeout(() => setTab(currRoute.name as keyof typeof barColors), 200);
}
});
return unsubscribe;
});
return (
<NavigationContainer ref={navRef}>
<Tab.Navigator
initialRouteName="home"
shifting={true}
activeColor="#e91e63"
barStyle={{
backgroundColor: barColors[tab],
}}>
<Tab.Screen
name="home"
component={HomeScreen}
options={{
tabBarColor: barColors.home,
tabBarLabel: 'Home',
tabBarIcon: ({color}) => (
<MaterialCommunityIcons name="home" color={color} size={26} />
),
}}
/>
<Tab.Screen
name="settings"
component={SettingsScreen}
options={{
tabBarColor: barColors.settings,
tabBarLabel: 'Settings',
tabBarIcon: ({color}) => (
<MaterialCommunityIcons name="cog" color={color} size={26} />
),
}}
/>
<Tab.Screen
name="profile"
component={ProfileScreen}
options={{
tabBarColor: barColors.profile,
tabBarLabel: 'Profile',
tabBarIcon: ({color}) => (
<MaterialCommunityIcons name="account" color={color} size={26} />
),
}}
/>
</Tab.Navigator>
</NavigationContainer>
);
};
const theme = {
...DefaultTheme,
colors: {
...DefaultTheme.colors,
secondaryContainer: 'transparent', // Use transparent to disable the little highlighting oval
},
};
export default function Main() {
return (
<Provider theme={theme}>
<App />
</Provider>
);
}

Navigate to other StackNavigator screen when press button on navbar

I'm pretty new to react and this is my first app.
I have a stack navigator with 2 screens by now: MainMenu and Profile. While the user is in MainMenu, a button on top right corner is shown and I need to redirect the user to the Profile screen when this button is pressed. I need something like this.props.navigation.navigate('Profile') but this does not work, because this, props and navigation are not defined.
My thinks are that I cannot redirect to Profile from this stack navbar, cause Profile is still defined yet, but I don't know another way to do it.
// mainStack.js
import React from 'react';
import { View, Text, TouchableOpacity, Image } from 'react-native';
import { createStackNavigator } from '#react-navigation/stack';
import MainMenu from '../../screens/home/mainMenu';
import Profile from '../../containers/profileContainer';
import Icon from 'react-native-vector-icons/FontAwesome';
import { useSelector } from 'react-redux';
const MainStack = () => {
const Stack = createStackNavigator();
const isAdmin = (useSelector(state => state.auth.user.role) === 'admin');
function renderUserMenu() {
return (
<TouchableOpacity style={{ marginRight: 20 }} onPress={() => console.log("HERE I NEED TO REDIRECT TO THE SCREEN PROFILE") } >
<Icon style={{ color: 'white' }} name='user-circle-o' size={30} />
</TouchableOpacity>
)
}
function LogoTitle() {
return (
<Image
style={{ width: 150, height: 50 }}
source={require('../../assets/logo-with-slogan.png')}
/>
);
}
function renderConfigBtn(_isAdmin) {
if (!_isAdmin) {
return (
<TouchableOpacity style={{ marginRight: 10 }} onPress={() => console.log('Configuraciones')} >
<Icon style={{ color: 'white' }} name='cog' size={30} />
</TouchableOpacity>
)
}
}
return (
<Stack.Navigator>
<Stack.Screen
name="MainMenu"
component={MainMenu}
options={{
headerTitle: props => <LogoTitle {...props} />,
headerRight: () => (
<View style={{ flexDirection: 'row' }}>
{renderConfigBtn(isAdmin)}
{renderUserMenu()}
</View>
),
headerStyle: { backgroundColor: '#0064c8' },
}}
/>
<Stack.Screen
name="Profile"
component={Profile}
options={{
headerStyle: { backgroundColor: '#0064c8' },
}}
/>
</Stack.Navigator>
)
}
export default MainStack;
Also, this stack is inside a navigation container as follows:
import React from 'react';
import { useSelector } from "react-redux";
import { NavigationContainer } from "#react-navigation/native";
import AuthStack from "./authStack";
import MainStack from "./mainStack";
const AppNavigator = props => {
const isAuth = useSelector(state => !!state.auth.access_token);
return (
<NavigationContainer>
{ !isAuth && <AuthStack/>}
{ isAuth && <MainStack/>}
</NavigationContainer>
);
};
export default AppNavigator;
I would appreciate any help.
You can access 'navigation' in options like below
options={({navigation})=>({
headerTitle: props => <LogoTitle {...props} />,
headerRight: () => (
<View style={{ flexDirection: 'row' }}>
{renderConfigBtn(isAdmin,navigation)}
{renderUserMenu(navigation)}
</View>
),
headerStyle: { backgroundColor: '#0064c8' },
})}
Basically you can pass a function as a prop to options and navigation will be passed to it as a parameter.
function renderUserMenu(navigation) {
return (
<TouchableOpacity style={{ marginRight: 20 }} onPress={() => navigation.navigate('YOUR SCREEN') } >
<Icon style={{ color: 'white' }} name='user-circle-o' size={30} />
</TouchableOpacity>
)
}
And you can change the renderUserMenu function like above so that it will do the navigation as required.
Use navigation options and then pass it to the function to navigate to profile:
<Stack.Screen
name="MainMenu"
component={MainMenu}
options={({ navigation }) => ({ ......
We simply can import the useNavigation hook from the react-navigation/native package and can implement navigation with the use of this hook without accessing the navigation props from the component.
For Ex.
First import the hook,
import { useNavigation } from '#react-navigation/native';
Use the hook to implement navigation as below in MainStack.js:
const navigation = useNavigation();
function renderUserMenu() {
return (
<TouchableOpacity style={{ marginRight: 20 }} onPress={() => navigation.navigate("Profile") } >
<Icon style={{ color: 'white' }} name='user-circle-o' size={30} />
</TouchableOpacity>
)
}

Pass props though screenstack

Im trying to pass some props to though an screenstack element in react native. I have a button which onPress will ask for a screen using react navigation like this:
<Button
title="Lees Meer"
color="#d10a10"
onPress={() => RootNavigation.navigate('Article', {
params: { title: title, text: text, image: image },
})}
/>
I want thos params to be used in the article to fill in the text, title and image. I thought I could just use them like this in the article:
function ArticleFull({ navigation, params }) {
return (
<View>
<Header/>
<Card>
<CardItem header bordered>
<Body>
<Image
style={{ width: '100%', height: 400 }}
source={{ uri: 'https://www.holland.com/upload_mm/9/a/b/68638_fullimage_zwolle_sassenpoort.jpg' }}
/>
<Text>
{params.text}
</Text>
</Body>
</CardItem>
</Card>
<Button
title="Go Back"
color="#d10a10"
width= "10%"
onPress={() => navigation.goBack()}
/>
</View>
);
}
export default ArticleFull;
In the app.js i made these screenstacks which is used to navigate to an article but i need it to contain some params which are set in the homepage using the button.
const Stack = createStackNavigator();
App.js:
export default class App extends Component {
render() {
return (
<NavigationContainer ref={navigationRef}>
<Stack.Navigator initialRouteName="Home" >
<Stack.Screen options={{headerShown: false}} name="Home" component={HomePage} />
<Stack.Screen options={{headerShown: false}} name="Article" component={ArticleFull} />
</Stack.Navigator>
</NavigationContainer>
);
}
}
You can pass like this:-
<Button
title="Go to Details"
onPress={() => {
/* 1. Navigate to the Details route with params */
navigation.navigate('Details', {
itemId: 86,
otherParam: 'anything you want here',
});
}}
/>
and receive like this:-
function DetailsScreen({ route, navigation }) {
/* 2. Get the param */
const { itemId } = route.params;
const { otherParam } = route.params;
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>itemId: {JSON.stringify(itemId)}</Text>
<Text>otherParam: {JSON.stringify(otherParam)}</Text>
);
}
source
Hope it helps!!!

Navigation back click event in React Native

I am working on a React Native application. I am using navigation in my application. I want to do something when user presses back navigation i.e. moved to a back screen.
How can i get the click event of "blacked circle Frage" in the above image. I am working on IOS
Use a custom header with
import { Header } from "native-base";
And add below code in your route file to disable default header.
navigationOptions: {
header: null
}
my custome header code for your reference
<Header style={styles.header}>
<View style={{ flex: 2 }}>
<TouchableOpacity
style={styles.iconButton}
onPress={() => { this.createNote(); this.props.navigation.navigate('Home') }}>
<Icon name="arrow-back" size={28} color="#606060" />
</TouchableOpacity>
</View>
<View style={{ flex: 8 }}></View>
<View style={{ flex: 2 }}>
<TouchableOpacity
style={styles.iconButton}
onPress={() => { this.createNote(); this.props.navigation.navigate('Home') }}>
<Icon name="check" size={28} color="#606060" />
</TouchableOpacity>
</View>
</Header>
reference link:- https://www.npmjs.com/package/native-base
It probably varies depending on the libraries you are using. I am using react-native-paper in Expo, which uses the headerLeft option in the Stack.Screen component. Here's a complete example - save it and then 'expo start'
import { Provider as PaperProvider, Text } from 'react-native-paper'
import { NavigationContainer } from '#react-navigation/native'
import { createNativeStackNavigator } from '#react-navigation/native-stack';
const Stack = createNativeStackNavigator();
export default function App() {
return (
<PaperProvider>
<NavigationContainer >
<Stack.Navigator>
<Stack.Screen
name="Example"
options={{
title: 'Example',
headerLeft: () => <Text>Custom left button</Text>,
}}
component={() => <Text>Example body text</Text>}
/>
</Stack.Navigator>
</NavigationContainer>
</PaperProvider>
)
}
You can use onPress={() => this.props.navigation.goBack()} on TouchableOpacity if you are redirecting to the previous page
Also you can use this.props.navigation.navigate('Any_Screen') to move to other screens.
Also, I would like to suggest you to get familiar with BackHandler to move back to previous page when hardware back button is pressed.
add the code
onClick={this.props.navigation.goBack()}
or use specif navigation replace go back to
onClick={this.props.navigation.navigate('namepagespacific')}
check this screen there are mutiple example of handling click event
import React from 'react';
import { View, Text, StyleSheet, Button} from 'react-native';
class DetailsScreen extends React.Component {
static navigationOptions = ({ navigation, navigationOptions, screenProps }) => {
return {
title: navigation.getParam('title', 'A Nested Details Screen'),
};
};
render() {
const { navigation } = this.props;
const itemId = navigation.getParam('itemId', 'NO-ID');
const otherParam = navigation.getParam('otherParam', 'some default value');
return (
<View style={styles.detailsScreen}>
<Text>Details Screen</Text>
<Text>itemId: {JSON.stringify(itemId)}</Text>
<Text>otherParam: {JSON.stringify(otherParam)}</Text>
<Button
title="Go to Details... again"
onPress={() => this.props.navigation.push('Details')}
/>
<Button
title="Go to Home"
onPress={() => this.props.navigation.navigate('Home')}
/>
<Button
title="Go back"
onPress={() => this.props.navigation.popToTop()}
/>
<Button
title="Update the title"
onPress={() => this.props.navigation.setParams({ title: 'Updated!' })}
/>
<Button
title="Modal"
onPress={() => this.props.navigation.navigate('MyModal')}
/>
</View>
);
}
}
const styles = StyleSheet.create({
detailsScreen: {
flex: 1,
alignItems: "center",
justifyContent: "center"
}
})
export default DetailsScreen;
things you have asked in the comment section I could not find any exact answer for your question but you can take a look into this url how header buttons work
https://snack.expo.io/#react-navigation/simple-header-button-v3
hope this will work for you
header: ({ goBack }) => ({
left: ( <Icon name={'chevron-left'} onPress={ () => { goBack() } } /> ),
}),
you can also follow this page https://github.com/react-navigation/react-navigation/issues/779