I want to move the screen with a button in React Native - react-native

I want to go to another screen by pressing the image button on the screen, but I don't know how. I am a complete beginner.
How can I go to the next page?
import React, { Component } from 'react'
import { StyleSheet, Text, View, TouchableOpacity,Image,Alert } from 'react-native';
import {} from 'react-navigation';
const ButtonScreen = props => {
const content = (
<View style= {[styles.button]}>
<Image source={require('../assets/icon/룰렛.png')} style={{
transform: [{scale: 0.37}],
}}
/>
</View>
)
return (
<TouchableOpacity onPress={() => {
Alert.alert('빨리');
}}
>{content}</TouchableOpacity>
)
}
const styles = StyleSheet.create ({
button: {
top: 60,
flexDirection: 'row',
alignItems: 'center',
height: '30%',
width: '100%',
},
})
export default ButtonScreen;

for navigation in react-native there are various libraries. react-navigation, react-native-router-flux, react-native-navigation(wix) are the ways you can use for navigation.
react-navigation is the famous one that currently has V5.x following by thorough documentation. It uses JavaScript codes for navigation and I assume you installed this library.
the react-native-router-flux use react-navigation V4.x and it really looks like react-router-dom in React-js. However I strongly suggest to not using that due to problems regarding performance.
react-native-navigation(wix) has the highest performance because it uses native codes for navigation. however it has poor document and it is really difficult for beginners to use.
In order to use the current version of react-navigation the first step you need to do is the installation of requirement then you need to have separate file for defining your routes. Lets assume you have two screens. the file looks like the following code:
import React from 'react';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import Screen1 from 'the path of Screen1'
import Screen2 from ' the path of Screen2'
const Stack = createStackNavigator();
function Navigation() {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Screen1" component={Screen1} />
<Stack.Screen name="Screen2" component={Screen2} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default Navigation
then you need to import this file on your index file.
import Navigation from "the path of Navigation";
AppRegistry.registerComponent(appName, () => Navigation);
if you are at ButtonScreen and you want to go on Screen2 you need the following code:
import React, { Component } from 'react'
import { StyleSheet, Text, View, TouchableOpacity,Image,Alert } from 'react-native';
const ButtonScreen = props => {
const content = (
<View style= {[styles.button]}>
<Image source={require('../assets/icon/룰렛.png')} style={{
transform: [{scale: 0.37}],
}}
/>
</View>
)
return (
<TouchableOpacity onPress={() => props.navigation.navigate("Screen2")}
>{content}</TouchableOpacity>
)
}
const styles = StyleSheet.create ({
button: {
top: 60,
flexDirection: 'row',
alignItems: 'center',
height: '30%',
width: '100%',
},
})
export default ButtonScreen;
this is the easiest way to navigate and I recommend you to read the document

Related

Opening a new page and sending a restAPI call on click of button in react Native

I am new to react native, started learning yesterday.
So, far my file structure is this:
---Assets
--- (some images)
---Screens
---WelcomeScreen.js
---Login.js
---app.js
---server.py (contains my flask API implementations)
I would like to navigate from WelcomeScreen to Login screen on clicking the login or register button inside WelcomeScreen and also send a rest API call to my backend so that I can further process the info.
app.js:
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View, SafeAreaView } from 'react-native';
import WelcomeScreen from './screens/WelcomeScreen';
export default function App() {
return (
<SafeAreaView style={styles.container}>
<WelcomeScreen />
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container:{
flex: 1,
width: "100%",
height: "100%",
}
})
WelcomeScreen.js
import React from 'react';
import { ImageBackground, StyleSheet, View, SafeAreaView, Text, Button } from 'react-native';
import Login from './Login';
function WelcomeScreen(props) {
return (
<ImageBackground
style={styles.background}
resizeMode="cover"
source={require("../assets/bg.jpg")}>
<Button
onPress={() => props.navigation.navigate(Login)} //throwing error
//TypeError: undefined is not an object (evaluating 'props.navigation.navigate')
title="Login"
color="#fc5c65"
/>
<Button
onPress={() => props.navigation.navigate(Login)} //throwing error
//TypeError: undefined is not an object (evaluating 'props.navigation.navigate')
title="Register"
color="#4ecdc4"
/>
</ImageBackground>
);
}
const styles = StyleSheet.create({
background:{
flex: 1,
justifyContent: "flex-end"
},
loginButton:{
width: "100%",
height: 70,
backgroundColor: '#fc5c65'
},
registerButton:{
width: "100%",
height: 70,
backgroundColor: '#4ecdc4'
},
})
export default WelcomeScreen;
Login.js
import React from 'react'
import { View, Text, StyleSheet } from 'react-native'
export default function Login() {
return (
<ImageBackground
style={styles.background}
resizeMode="cover"
source={require("../assets/splash.png")}>
</ImageBackground>
)
}
const styles = StyleSheet.create({
background:{
flex: 1,
justifyContent: "flex-end"
},
loginButton:{
width: "100%",
height: 70,
backgroundColor: '#fc5c65'
},
registerButton:{
width: "100%",
height: 70,
backgroundColor: '#4ecdc4'
},
})
Now, from the WelcomeScreen.js,
I want to go to the login page upon clicking login button or register button and also send a restAPI call to the backend.
How do I do this??
Navigation isn't always built in to react native. Primarily people use libraries to handle this smoothly. Based on your code, you've been following an example based on using react-navigation which you can read about here. Essentially you'll need nest all of your screens inside of special components from that library which will pipe the navigation prop through to your screen components.
In order to run the API calls, you can add those functions calls on a new line in each of the functions you are passing as the onPress prop. Alternatively, you could place a useEffect hook in your screen components to make the API call after the navigation has completed.
// in Login.js
export const Login = () => {
useEffect(() => {
callAPI()
}, []);
...
}

react-native: How to hide an element in createStackNavigator [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have a stackNavigator is displayed in my menu with my configuration
const ProfileStack = createStackNavigator();
function ProfileNavigator() {
return (
<ProfileStack.Navigator
drawerStyle={{ width: '100%', color: 'red' }} // not work
>
<ProfileStack.Screen
name="ProfileScreen"
component={ProfileScreen}
options={{
headerBackTitleVisible: false, // not work
headerMode: 'none',
headerShown: true // work
}}
/>
</ProfileStack.Navigator>
)
}
( I have profile in menu ( red border ) and button profile ( icon )
And i want to keep the button, hide in the menu and keep the header in the webpage/view.
I try many conf with the documentation ( https://reactnavigation.org/docs/4.x/stack-navigator-1.0#navigationoptions-for-screens-inside-of-the-navigator )
I would like hide the element of the menu. Because the page/view is accessible from a button.
I check many configurations of createStackNavigator.
headerBackTitleVisible and others didn't work.
Do you know how to hide an element bevcause i'm lost :( ?
thanks
Take a look at this React Navigation Github issue. The person who posted that wanted to hide an item in the drawer menu, but still be able to access the drawer from that page. The following workaround was provided:
I found the following workaround :
Create a component returning null
Pass the component to the drawerLabel navigationOptions of the screen you want the item to be hidden
Hope this helps.
Here is an example below, which you can copy, paste, and run if you would like:
App.js:
import React from 'react';
import TestAppContainer from "./TestAppContainer";
export default function App() {
return (
<TestAppContainer/>
);
}
TestAppContainer.js:
import React from "react";
import {NavigationContainer} from "#react-navigation/native";
import {DrawerNavigatorTest} from "./NavigatorTest";
const TestAppContainer = props => {
return (
<NavigationContainer>
<DrawerNavigatorTest />
</NavigationContainer>
);
}
export default TestAppContainer;
NavigatorTest.js:
import React from "react";
import {createDrawerNavigator} from "#react-navigation/drawer";
import TestScreen from "./TestScreen";
import TestScreenTwo from "./TestScreenTwo";
import NullComponent from "./NullComponent";
const TestDrawerNavigator = createDrawerNavigator();
export const DrawerNavigatorTest = () => {
return(
<TestDrawerNavigator.Navigator drawerContentOptions={{activeBackgroundColor: "transparent"}}>
<TestDrawerNavigator.Screen name={"Test"} component={TestScreen} />
<TestDrawerNavigator.Screen name={"Test2"} component={TestScreenTwo} options={{drawerLabel: NullComponent}}/>
</TestDrawerNavigator.Navigator>
);
}
NullComponent.js:
import React from "react";
const NullComponent = props => {
return null;
}
export default NullComponent;
TestScreen.js:
import React from "react";
import {SafeAreaView, View, Text, Button} from "react-native";
const TestScreen = props => {
const buttonPressHandler = () => {
props.navigation.navigate("Test2");
};
return (
<SafeAreaView style={{flex: 1,}}>
<View style={{flex: 1, alignItems: "center", justifyContent: "center"}}>
<Text>Test Screen</Text>
<Button title={"Go to next screen."} onPress={buttonPressHandler} />
</View>
</SafeAreaView>
);
};
export default TestScreen;
TestScreenTwo.js:
import React from "react";
import {SafeAreaView, View, Text} from "react-native";
const TestScreenTwo = props => {
return (
<SafeAreaView style={{flex: 1,}}>
<View style={{flex: 1, alignItems: "center", justifyContent: "center"}}>
<Text>Test Screen Two</Text>
</View>
</SafeAreaView>
);
};
export default TestScreenTwo;
Note that this is not a perfect solution, but a workaround. It could use some more fine tuning. You may also want to look into custom drawer components. I'm not very familiar with custom drawer components, but you may be able to get cleaner functionality with custom drawer items. See the React Navigation Docs.

TypeError: undefined is not an object (evaluating props.navigation.navigate)

I have an icon on the right side of my Header. When pressed I want to be transferred to another page. However, it comes up with an error.
This is my 'icon' screen:
import React, { Component } from 'react';
import { StyleSheet, View, Text, Image, TouchableOpacity } from 'react-native';
const Login = props => {
return (
<View style={{ flexDirection: 'row' }}>
<TouchableOpacity
onPress={() => {
props.navigation.navigate({routeName: 'Login'});}}>
<Image
source={{
uri:
'https://clipartart.com/images/login-icon-clipart-5.jpg',
}}
style={{
width: 40,
height: 40,
borderRadius: 40 / 2,
marginLeft: 15,
}}
/>
</TouchableOpacity>
</View>
);
}
export default Login;
This is my 'navigation' screen:
import {createStackNavigator} from 'react-navigation-stack';
import {createAppContainer} from 'react-navigation';
import React from 'react';
import Homepage from './screens/Homepage';
import Checkoutpage from './screens/Checkoutpage';
import Filterpage from './screens/Filterpage';
import Locationpage from './screens/Locationpage';
import Menupage from './screens/MenuPage';
import Welcomepage from './screens/Welcomepage';
import Loginpage from './screens/Loginpage';
import Finalpage from './screens/Finalpage';
import Login from './Components/Login';
const Navigation = createStackNavigator({
Home:Homepage,
Checkout: Checkoutpage,
Filter: Filterpage,
Location: Locationpage,
Menu: Menupage,
Welcome: Welcomepage,
Login: Loginpage,
Final: Finalpage
},
{
defaultNavigationOptions: {
headerRight:() => <Login/>
}
}
);
I'm very new to react-native. So if you found the problem, can you please explain thoroughly so I understand. Thank you!!
So it looks like you are expecting the navigation object to be part of the props passed to your <Login/> component. This object is only defined for screen components in react-navigate.
This means that you need to get access to the navigation functionality some other way. Luckily, this library provides you with the useNavigation() hook. So using that in your component would look something like:
// react-navigation v5+
import { useNavigation } from '#react-navigation/native';
const Login = () => {
const navigation = useNavigation();
return (
<View style={{ flexDirection: "row" }}>
<TouchableOpacity
onPress={() => {
navigation.navigate({ routeName: "Login" });
}}
>
<Image
source={{
uri: "https://clipartart.com/images/login-icon-clipart-5.jpg",
}}
style={{
width: 40,
height: 40,
borderRadius: 40 / 2,
marginLeft: 15,
}}
/>
</TouchableOpacity>
</View>
);
};
It seems to me you are using React Navigation v4.x , in order to use the useNavigation hook you need to upgrade to v5.x.
The navigation prop will be passed to all screens by default and you can use the useNavigation hook like #faelks suggested (if needed in other components).
UPGRADE TO v5 FIRST.
Here you have a little example for v5.x version:
import React from 'react'
import { Button, View, StyleSheet } from 'react-native'
import { NavigationContainer } from '#react-navigation/native'
import { createStackNavigator } from '#react-navigation/stack'
const Home = ({ navigation }) => (
<View style={styles.component}>
<Button title="Go to login" onPress={() => navigation.navigate('Login')} />
</View>
)
const Login = ({ navigation }) => (
<View style={styles.component}>
<Button title="Go back" onPress={() => navigation.goBack()} />
</View>
)
const Main = createStackNavigator()
const mainConfig = {
// configuration for this stack
initialRouteName: "Home",
}
export default props => (
<NavigationContainer>
<Main.Navigator {...mainConfig}>
<Main.Screen name="Home" component={Home} />
<Main.Screen name="Login" component={Login} />
{/* Other screens for this stack */}
</Main.Navigator>
</NavigationContainer>
)
const styles = StyleSheet.create({
component: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
}
})

React-native header title image is cut off, why?

So I'm working on a react-native application and I am using react-navigation for my navigation, using an image in the headerTitle in the screen options works however the image is cut off. I've tried messing with the height/width of the image, wondered if it was a padding issue with the header yet still nothing. Any ideas why?
Here is the component
import React from "react";
import { View, Image, StyleSheet } from "react-native";
function HeaderLogo(props) {
return(
<Image style={styles.logoStyles} source={require("../../assets/images/svg/LogoNoTxt.png")}/>
);
};
const styles = StyleSheet.create({
logoStyles: {
height: 40,
width: 40,
},
});
export default HeaderLogo
Here is the stack navigator
import React from "react";
import { createStackNavigator } from '#react-navigation/stack';
//Components
import HeaderLogo from "../../components/images/HeaderLogo";
//TopTab
import HomeTopTabNavigator from "../topTab/HomeTopTabNavigator";
//Screens
import AddTasks from "../../screens/home/AddTasks";
//Initialize vars
const Stack = createStackNavigator();
function HomeStackNavigator() {
return(
<Stack.Navigator screenOptions={defaultOptions}>
<Stack.Screen name="Home" component={HomeTopTabNavigator}/>
<Stack.Screen name="AddTasks" component={AddTasks}/>
</Stack.Navigator>
);
};
//Options
const defaultOptions = {
headerStyle: {
elevation: 0,
shadowColor: "transparent",
},
//headerTitleAlign: "center",
headerTitle: (
<HeaderLogo />
),
headerTitleAlign: "center",
};
export default HomeStackNavigator;
Image of Logo on the header (cut off)
Just wrapped the component in a function, and it rendered properly.
For posterity:
headerTitle: () => <HeaderLogo />

React Native Drawer navigation

Hi there I am trying to implement a drawer navigation in React Native
referring to this example.
I have almost finished the coding but I am getting an error while adding the contentComponent attribute in drawer class (HomeScreenRouter). After removing it I am able to run it successfully and everything is working well but when I add the sidebar menu using contentComponent it throws an error. I need a custom design for my drawer.
Here is my code for the drawer:
import React, { Component } from "react";
import HomeScreen from "./HomeScreen.js";
import MainScreenNavigator from "../DealScreen/mychat.js";
import Profiled from "../profilescreen/Profile.js";
import SideBar from "../SideBar/SideBar.js";
import { DrawerNavigator } from "react-navigation";
const HomeScreenRouter = DrawerNavigator(
{
Home: { screen: HomeScreen },
Chat: { screen: MainScreenNavigator },
Profile: { screen: Profiled },
},
{
contentComponent: props => <SideBar {...props} />
});
export default HomeScreenRouter;
Sidemenu :
import React from "react";
import { AppRegistry, Image, StatusBar } from "react-native";
import { Container, Content, Text, List, ListItem } from "native-base";
export default class SideBar extends React.Component {
render() {
const routes = ["Home", "Chat", "Profile"];
return (
<Container>
<Content>
<Image
source={{
uri: "https://github.com/GeekyAnts/NativeBase-KitchenSink/raw/react-navigation/img/drawer-cover.png"
}}
style={{
height: 120,
alignSelf: "stretch",
justifyContent: "center",
alignItems: "center"
}}>
<Image
square
style={{ height: 80, width: 70 }}
source={{
uri: "https://github.com/GeekyAnts/NativeBase-KitchenSink/raw/react-navigation/img/logo.png"
}}
/>
</Image>
<List
dataArray={routes}
renderRow={data => {
return (
<ListItem
button
onPress={() => this.props.navigation.navigate("Profile")}>
<Text>{data}</Text>
</ListItem>
);
}}
/>
</Content>
</Container>
);
}
}