React Native Button navigate to another page - javascript

I'm new to React Native. I need that if I click on a button, a new page appears. I already tried a few things but maybe the problem is somewhere else.
I will paste my code underneath. Please help me :)
Further explanation: I want to click on the button and then it should go to another page.
import React, { useState } from "react";
import {
StyleSheet,
Text,
View,
Image,
TextInput,
TouchableOpacity,
Linking,
Button
} from "react-native";
import { useNavigation } from '#react-navigation/native';
import "react-native-gesture-handler";
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator, createAppContainer } from 'react-navigation';
export default function App() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
return (
<View style={styles.container}>
<Image style={styles.image} source={require("./assets/logo.png")} />
<StatusBar style="auto" />
<View style={styles.inputView}>
<TextInput
style={styles.TextInput}
placeholder="Benutzername"
onChangeText={(email) => setEmail(email)}
/>
</View>
<Button
style={styles.loginBtn}
title="Go to Profile"
onPress={() => this.props.navigation.navigate('Profile')}
/>
</View>
);
}
```

Might be this helpful to you:
MyNavigation Version
#react-navigation/native": "^5.9.8"
#react-navigation/stack": "^5.14.9"
Example
import React from 'react';
import {View, Text, StyleSheet, TouchableOpacity} from 'react-native';
//Navigation import
import {NavigationContainer} from '#react-navigation/native';
import {createStackNavigator} from '#react-navigation/stack';
//Screen One
const ScreenOne = props => {
//onPress To Navigate
const onPress = () => {
props.navigation.navigate('ScreenTwo');
};
return (
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<TouchableOpacity onPress={onPress}>
<Text>Hello From Screen One</Text>
</TouchableOpacity>
</View>
);
};
//Screen Two
const ScreenTwo = () => {
return (
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<Text>Screen Two</Text>
</View>
);
};
const App = () => {
//const
const Stack = createStackNavigator();
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="ScreenOne" component={ScreenOne} />
<Stack.Screen name="ScreenTwo" component={ScreenTwo} />
</Stack.Navigator>
</NavigationContainer>
);
};
export default App;

Related

React navigation params object empty

When i try passing the params to my review screen it comes up undefined.
I'm using "#react-navigation/native": "^6.1.3" and "#react-navigation/stack": "^6.3.12"
App.js
import 'react-native-gesture-handler';
import { StyleSheet, Text, View, Button, TouchableOpacity, FlatList } from 'react-native';
import {NavigationContainer} from '#react-navigation/native';
import Stack from './routes/stack';
export default function App() {
return (
<NavigationContainer>
<Stack/>
</NavigationContainer>
);
}
Stack.js
import {createStackNavigator} from '#react-navigation/stack';
import ReviewScreen from '../screens/Reviews';
import HomeScreen from '../screens/Home';
import AboutScreen from '../screens/About';
const stack = createStackNavigator();
const Stack = () => {
return(
<stack.Navigator>
<stack.Screen name="Home" component={HomeScreen} />
<stack.Screen name="Review" component={ReviewScreen} />
</stack.Navigator>
)}
export default Stack;
HomeScreen
<View style={{width: 100, alignItems: "center"}}>
<TouchableOpacity style={{backgroundColor: "#333", padding: 10, borderRadius: 15, margin: 10}}
onPress={() => navigation.navigate("Review",
{title:"Title Name"}
)}
>
<Text style={{color: "white"}}>{item.title}</Text>
</TouchableOpacity>
</View>
Review.js
import {View, Text, Button} from 'react-native';
import React from 'react';
export default ReviewScreen = ({ navigation, route }) => {
console.log(route);
const { title } = route.params;
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Review Screen</Text>
<Button
title="Go to Home"
onPress={() => navigation.goBack()}
/>
</View>
);
};
When I send the object from the home page to the review screen the destructed title throws an undefined error and when I log the route object it shows that the params value is undefined.
console logged route object
{"key": "Review-xxx", "name": "Review", "params": undefined, "path": undefined}
How can I get the params to pass onto the review screen properly?
here is the working code see it!
App.js
import * as React from 'react';
import { Button, View, Text, TouchableOpacity } from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
function HomeScreen({ navigation }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<Button
title="Go to Details"
onPress={() => navigation.navigate('Details',{ title:"Full Stack Developer"})}
/>
</View>
);
}
function DetailsScreen({ navigation, route }) {
const { title } = route.params;
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>{title}</Text>
</View>
);
}
const Stack = createNativeStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Details" component={DetailsScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;
I had not properly installed the #react-navigation/native and #react-navigation/stack dependencies. Find them stated here and here respectively.

Application Breaks when adding custom component as import

I am having an issue where I have created two components "TaskInputField.js" and "TaskItem.js" and when I import them into the file I want to use them in, the browser window I am viewing the app on turns completely blank (using expo). Can post screenshots of what I mean if needed.
This has never happened to me before where simply importing a file breaks the application.
If I remove the imports from GroceryList.js and remove where I use them in the file, everything else runs just fine. I followed a guide for most of this also so I am unsure what is happening.
Thanks in advance.
For reference:
TaskInputField.js
import React, {useState} from 'react';
import { KeyboardAvoidingView, StyleSheet, View, TextInput, TouchableOpacity, } from "react-native";
import { MaterialIcons } from '#expo/vector-icons';
export default TaskInputField = (props) => {
const [task, setTask] = useState();
const handleAddTask = (value) => {
props.addTask(value);
setTask(null);
}
return (
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : "height"}
style={styles.container}
>
<TextInput style={styles.inputField} value={task} onChangeText={text => setTask(text)} placeholder={'Write a task'} placeholderTextColor={'#fff'}/>
<TouchableOpacity onPress={() => handleAddTask(task)}>
<View style={styles.button}>
<MaterialIcons name="keyboard-arrow-up" size={24} color="black" />
</View>
</TouchableOpacity>
</KeyboardAvoidingView>
);
}
TaskItem.js
import React from 'react';
import { StyleSheet, Text, View, TouchableOpacity, } from "react-native";
import { MaterialIcons } from '#expo/vector-icons';
export default TaskItem = (props) => {
return (
<View style={styles.container}>
<View style={styles.indexContainer}>
<Text style={styles.index}>{props.index}</Text>
</View>
<View style={styles.taskContainer}>
<Text style={styles.task}>{props.task}</Text>
<TouchableOpacity onPress={() => props.deleteTask()}>
<MaterialIcons style={styles.delete} name="delete" size={18} color='#fff' />
</TouchableOpacity>
</View>
</View>
);
}
I am implementing these here in GroceryList.js
import React, {useState} from 'react';
import { Keyboard, ScrollView, StyleSheet, Text, View } from 'react-native';
import TaskInputField from '../../components/TaskInputField';
import TaskItem from '../../components/TaskItem';
export default function GroceryList() {
const [tasks, setTasks] = useState([]);
const addTask = (task) => {
if (task == null) return;
setTasks([...tasks, task]);
Keyboard.dismiss();
}
const deleteTask = (deleteIndex) => {
setTasks(tasks.filter((value, index) => index != deleteIndex));
}
return(
<View style={styles.container}>
<Text style={styles.heading}>Grocery List</Text>
<ScrollView style={styles.scrollView}>
{
tasks.map((task, index) => {
return (
<View key={index} style={styles.taskContainer}>
<TaskItem index={index + 1} task={task} deleteTask={() => deleteTask(index)}/>
</View>
);
})
}
</ScrollView>
<TaskInputField addTask={addTask}/>
</View>
)
}

TypeError: Cannot read property 'navigate' of undefined React Native

Here's a Stack Navigator inside a MainStack.js:
import React from 'react'
import { createStackNavigator } from '#react-navigation/stack';
import Main from './Main'
import ScannerMarker from './ScannerMarker';
const Stack = createStackNavigator();
export default function MainStack() {
return(
<Stack.Navigator initialRouteName='Main' screenOptions={{headerShown: false}}>
<Stack.Screen name='Main' component={Main} />
<Stack.Screen name='ScannerMarker' component={ScannerMarker} />
</Stack.Navigator>
);
}
And ScannerMarker.js:
import React from 'react';
import { StyleSheet, View, Text, Dimensions, Pressable } from 'react-native';
import MaterialIcon from 'react-native-vector-icons/MaterialIcons';
import Feather from 'react-native-vector-icons/Feather';
import Octicon from 'react-native-vector-icons/Octicons'
import Main from './Main';
export default function ScannerMarker({ navigation, setModalVisible }) {
return (
<View style={styles.markerContainer}>
<View style={styles.topContainer}>
<View style={styles.topBar}>
<MaterialIcon name="support-agent" size={32} color="#fffeef" backgroundColor={'none'} onPress={() => navigation.navigate(Main)} />
<Feather name="x" size={32} color="#fffeef" backgroundColor={'none'} onPress={() => navigation.goBack(Support)}/>
</View>
<Text style={styles.topText}>Point scanner to{'\n'}vending qr-code</Text>
</View>
<View style={styles.middleContainer}>
<View style={styles.leftContainer}></View>
<View style={styles.scannerSquare}></View>
<View style={styles.rightContainer}></View>
</View>
<View style={styles.bottomContainer}>
<Pressable style={styles.button} onPress={() => setModalVisible(false)}>
<Octicon name="number" size={20} color="#fffeef" style={styles.chargerIcon}/>
<Text style={styles.buttonText}> Enter vending{'\n'}number</Text>
</Pressable>
</View>
</View>
)
}
ScannerMarker is a part of a Scanner in Scanner.js:
import React from 'react';
import { StyleSheet, Linking, Dimensions} from 'react-native';
import QRCodeScanner from 'react-native-qrcode-scanner';
import { RNCamera } from 'react-native-camera';
import ScannerMarker from './ScannerMarker';
export default function Scanner({ modalVisible, setModalVisible }) {
onSuccess = e => {
Linking.openURL(e.data)
setModalVisible(!modalVisible)
};
return (
<QRCodeScanner
onRead={this.onSuccess}
flashMode={RNCamera.Constants.FlashMode.auto}
cameraStyle={styles.cameraStyle}
showMarker={true}
customMarker={
<ScannerMarker setModalVisible={setModalVisible}> </ScannerMarker>
}
/>
);
}
MainStack is rendered inside a Drawer Navigator in Drawer.js:
import React from 'react';
import { StyleSheet, View, Linking} from 'react-native';
import { createDrawerNavigator, DrawerItemList, DrawerContentScrollView, DrawerItem} from '#react-navigation/drawer';
import MaterialCommunityIcon from 'react-native-vector-icons/MaterialCommunityIcons';
const Drawer = createDrawerNavigator();
export default function MyDrawer(props) {
return (
<Drawer.Navigator
...
>
<Drawer.Screen
name='MainStack'
component={MainStack}
options={{
title: 'Charge Away',
drawerIcon: () => (<MaterialCommunityIcon name="lightning-bolt" size={45} color="#2E2A00" style={{marginEnd: -30, marginStart: -10}} />)
}}
/>
...
<Drawer.Navigator>
);
}
When i press on icons with "onPress={() => navigation.navigate(...)}" or onPress={() => navigation.goBack()} I get the following errors:
TypeError: Cannot read property 'navigate' of undefined and TypeError: Cannot read property 'goBack' of undefined
So I don't know what's the problem. navigation parametr is declared and all of the components are in the Stack Navigator.
Everything is wrapped in NavigationContainer in App.js:
import * as React from 'react';
import { NavigationContainer} from '#react-navigation/native';
import MyDrawer from './components/Drawer'
export default function App() {
return (
<NavigationContainer>
<MyDrawer />
</NavigationContainer>
);
}
I've solved the problem using useNavigation function:
import { View, Button } from 'react-native';
import { useNavigation } from '#react-navigation/native';
export default function MyComp() {
const navigation = useNavigation();
return (
<View>
<Button
title="Go to Home"
onPress={() => navigation.navigate('Home')}
/>
</View>
);
};
Another option is to pass navigation to MyComp with props:
export default function MyComp( {navigation} ) {
//...
};
<MyComp navigation={props.navigation} />
Source:
https://reactnavigation.org/docs/connecting-navigation-prop

React Native: undefined is not an object (evaluating 'props.navigation.navigate')

I'm learning React Native and by trying to run this code using Expo it gives me the Exception error:
undefined is not an object (evaluating 'props.navigation.navigate'), at line 17 on App.js (marked in the comment)
There are two files: App.js and Untitled1.js
App:
import { StyleSheet, Text, View, TextInput, TouchableOpacity } from 'react-native';
import 'react-native-gesture-handler';
import { NavigationContainer } from '#react-navigation/native';
function App(props) {
return (
<View style={styles.container}>
<Text style={styles.logo}>APPetito</Text>
<Text style={styles.loginText}>Welcome to our app!</Text>
<Text style={styles.loginText}>Choose what do you want to do</Text>
// [ THE FOLLOWING LINE CONTAINS THE ERROR ]
<TouchableOpacity onPress={() => props.navigation.navigate("Untitled1")} style={styles.loginBtn}>
<Text style={styles.loginText}>I eat food</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.loginBtn}>
<Text style={styles.loginText}>I sell food</Text>
</TouchableOpacity>
</View>
);
}
// here there are the const styles
export default App;
Untitled.js
import * as React from 'react';
import React, { Component } from "react";
import { StyleSheet, View, Text } from "react-native";
import Icon from "react-native-vector-icons/Entypo";
import { NavigationContainer } from '#react-navigation/native';
function Untitled1(props) {
return (
<View style={styles.container}>
<Icon name="check" style={styles.icon}></Icon>
<Text style={styles.itWorks}>It works!</Text>
</View>
);
}
// here there are the const styles
export default Untitled1;
What can I do to solve the problem?
I think the problem is that you didn't create a Stack navigator in the first place to navigate between screens. Refer to react navigation docs to know more here
According to the docs you have to implement the stack navigator such as:
import * as React from 'react';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
function Home(props) {
return (
<View style={styles.container}>
<Text style={styles.logo}>APPetito</Text>
<Text style={styles.loginText}>Welcome to our app!</Text>
<Text style={styles.loginText}>Choose what do you want to do</Text>
<TouchableOpacity onPress={() => props.navigation.navigate("Untitled1")} style={styles.loginBtn}>
<Text style={styles.loginText}>I eat food</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.loginBtn}>
<Text style={styles.loginText}>I sell food</Text>
</TouchableOpacity>
</View>
);
}
const Stack = createStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={Home} />
<Stack.Screen name="Untitled1" component={Untitled1} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;
I have updated your code a little bit to help you understand the concept.

React Native: React-Navigation Cannot read property 'navigate' of undefined

I am currently learning React Native and was having some issue with React-navigation.
What I am trying to do is switch screen when the "button" is being pressed.
In the "button", I have:
onPress={() =>
navigate('Home')}
I have const { navigate } = this.props.navigation; before the return statement.
When I run it, I am getting "Cannot read property 'navigate' of undefined.
I guess it is I have to place this.props.navigation somewhere.
Here are my two files:
"IntroPageFive" is the one that has the button and "react-navigation".
I would like to go to "IntroPageOne" when the button is being clicked.
Code for "IntroPageFive":
import React from 'react';
import { Text, View, Image, Linking, Button, TouchableOpacity } from 'react-native';
import PlaceholderImage from '../images/placeholder_thumbnail.png';
import SignInFooter from './signInFooter';
import { createStackNavigator } from 'react-navigation';
import IntroPageOne from './introPageOne';
const App = createStackNavigator({
Home: { screen: IntroPageOne },
});
class IntroPageFive extends React.Component {
render() {
const {
headerTextStyle,
thumbnailStyle,
viewStyle,
subTextStyle,
mainTextSection,
footerSectionStyle,
startButtonStyle,
startButtonTextStyle,
signInButtonStyle ,
signInButtonTextStyle
} = styles;
const { navigate } = this.props.navigation;
return (
<View style={viewStyle}>
<Image style={thumbnailStyle} source={require('../images/placeholder_thumbnail.png')} />
<View style={mainTextSection}>
<Text style={headerTextStyle}>Take A Ride For</Text>
<Text style={headerTextStyle}>Your Favorite Car!</Text>
</View>
<View>
<TouchableOpacity
onPress={() =>
navigate('Home')
}
style={startButtonStyle}
>
<Text style={startButtonTextStyle}>LET'S GET STARTED</Text>
</TouchableOpacity>
</View>
<View style={footerSectionStyle}>
<SignInFooter />
</View>
</View>
);
}
}
export default IntroPageFive;
Here is the code for "IntroPageOne":
import React from 'react';
import { Text, View, Image, Linking } from 'react-native';
import PlaceholderImage from '../images/placeholder_thumbnail.png';
import SignInFooter from './signInFooter';
const IntroPageOne = () => {
const { headerTextStyle, thumbnailStyle, viewStyle, subTextStyle } = styles;
return (
<View style={viewStyle} >
<Image style={thumbnailStyle} source={require('../images/placeholder_thumbnail.png')} />
<Text style={headerTextStyle}>Forget Everything You</Text>
<Text style={headerTextStyle}>Know About Making</Text>
<Text style={headerTextStyle}>Deals For Your Car</Text>
<Text style={subTextStyle}>Deal negotiation powered by AI</Text>
<SignInFooter />
</View>
);
};
};
export default IntroPageOne;
Could anyone please tell me how to fix this issue?
Thank you.

Categories