I am new to React Native. I am trying to render a button conditional on the value of a 'global' value. This is incredibly frustrating.
Normally it would be a simple case of using an 'if/else' statement to accomplish this in Javascript or nearly any other language. Apparently this is not possible in React Native. Here is my code:
import React, { useState } from 'react';
import { Button, Text, TextInput, View } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
function HomeScreen({ navigation }) {
const [isLogged, setLog] = useState(0);
return (
<>
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
</View>
{isLogged === 0 ? (<Button title="Go to Login"> onPress={() => navigation.navigate('Login')} </Button>) : (<Button title="Do Stuff"> onPress={() => navigation.navigate('Stuff')} </Button>)}
</>
);
}
function LoginScreen({ navigation }) {
//do things to login here
}
function StuffScreen({ navigation }) {
//do other things here
}
const Stack = createStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Login" component={LoginScreen} />
<Stack.Screen name="Stuff" component={StuffScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;
This code above correctly renders a 'Home' screen with a button that reads 'Go to Login' as it should. However the 'OnPress' statement attached to the button is not functional...nothing happens when pressing the button on the phone. If I were to simply insert a button with the 'OnPress' assigned singly, without the ternary operator statement, I can get the button to be functional.
Can somebody please explain why the 'OnPress' is not functioning when the button is used within a ternary operator? In addition would I be able to change the value of 'isLogged' in another function (for example the 'Login') and have this correctly pass to the 'Home' screen?
Why are simple tasks that could be handled with 'if/else' statements so challenging in React Native? This is driving me crazy...I thank you in advance.
The way you are providing the onpress is wrong. You are providing it as a child but it should be a prop like below.
{isLogged === 0 ? (
<Button
title="Go to Login"
onPress={() => navigation.navigate('Login')}
/>
) : (
<Button
title="Do Stuff"
onPress={() => navigation.navigate('Stuff')} />
)
}