I am new to Javascript and React Native and I’m confused why the following code doesn’t navigate me to my other screen:
const Stack = createNativeStackNavigator();
export default function App() {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName = "Home">
<Stack.Screen name = "Home" component = {HomeScreen} />
<Stack.Screen name = "Login" component = {LoginScreen} />
<Stack.Screen name = "Register" component = {RegisterScreen}/>
<Stack.Screen name = "Hub" component = {HubScreen}/>
<Stack.Screen name = "NewList" component = {NewListScreen}/>
</Stack.Navigator>
</NavigationContainer>
);
}
function RegisterScreen({navigation}) {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
return (
<View style={styles.container}>
<Text style={styles.label}>Registration</Text>
<TextInput
style={styles.input}
placeholder="Username"
onChangeText={(text) => setUsername(text)}
/>
<TextInput
style={styles.input}
placeholder="Password"
onChangeText={(text) => setPassword(text)}
/>
<Button
title="Register"
onPress = {() => Register(username, password)}
/>
</View>
)
}
function Register(username, password){
Alert.alert("All Done!", "You have successfully registered.", {text: "OK", onPress: () => {navigation.navigate('Home')}})
}
I want function Register to show an alert where the user can press ok and for them to be redirected back to the home screen. The alert apears however pressing okay doesn’t navigate back to the Home screen. From what I’ve read on the React Native Navigation docs function Register somehows needs access to navigation parameter but im confused on how to practically do that.
I tried using useNavigation();
but I kept getting a hook call error.
I have also tried NavigationRef but with no success. I have also tried putting Register
inside RegisterScreen
. Also tried having navigation
as a parameter of Register
. No change in output.
2
Answers
try put
Register
function insideRegisterScreen
edit:
The third prop of Alert.alert is an object array, i wonder why you didn’t get an error there
you should define the
Register()
inside theRegisterScreen
component like following..or you can pass the navigation in Register function params like this
and you can see
user_array
is not defined hereand what is the meaning of this line
const user = new User(username, password);