pass value from one componet to another in react natve - javascript

i am trying to pass value from login and register into dashbord since sign is a unique compont i dont know how to pass log from login and register can someone help
sign.js
export default function Sign({navigation}) {
async function onGoogleButtonPress() {
await GoogleSignin.hasPlayServices();
const userInfo = await GoogleSignin.signIn();
setuserInfo(userInfo);
navigation.navigate('dash', {userInfo});
}
return (
<View style={styles.prheight}>
<View style={styles.buttonw}>
<GoogleSigninButton
style={{width: 192, height: 48}}
size={GoogleSigninButton.Size.Wide}
color={GoogleSigninButton.Color.Light}
onPress={onGoogleButtonPress}
// disabled={this.state.isSigninInProgress}
/>
</View>
</View>
);
}
register.js
export default function Register(props) {
return (
<View style={styles.prheight}>
<View style={styles.buttonw}>
<Sign navigation={props.navigation} log={name:"register"} />
</View>
</View>
);
}
login
export default function login(props) {
return (
<View style={styles.prheight}>
<View style={styles.buttonw}>
<Sign navigation={props.navigation} log={name:"login"} />
</View>
</View>
dash.js
export default function dash(props) {
const [text, setTextbaby] = useState();
const {userInfo} = props?.route?.params;
console.log(props.log);

You should pass log prop in Sign component and take it like this.
export default function Sign({ navigation, log }) {
async function onGoogleButtonPress() {
await GoogleSignin.hasPlayServices();
const userInfo = await GoogleSignin.signIn();
setuserInfo(userInfo);
navigation.navigate('dash', {userInfo, log});
}
// some code
}
after all, log will be located inside props.route.params object
export default function dash(props) {
const [text, setTextbaby] = useState();
const {userInfo, log} = props?.route?.params;
console.log(log);
}
UPDATED: use double brackets (in order to pass object)
log={{name: "register"}}
log={{name: "login"}}

we can pass a value from one screen to another screen through async-storage react-navigation or declare a value globally.
To pass a value from login to dashboard I recommend you to see this async-storage Docs https://react-native-async-storage.github.io/async-storage/docs/install
async-storage store a value in App while React navigation does not store a value in App, React navigation just transfer value from one screen to another.
react navigation Docs https://reactnavigation.org/docs/navigating/
passing a value from one component to another
import { Text, View, Button } 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={() => {
/* 1. Navigate to the Details route with params */
navigation.navigate('Details', {
itemId: 86,
otherParam: 'anything you want here',
});
}}
/>
</View>
);
}
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>Details Screen</Text>
<Text>itemId: {JSON.stringify(itemId)}</Text>
<Text>otherParam: {JSON.stringify(otherParam)}</Text>
<Button
title="Go to Details... again"
onPress={() =>
navigation.push('Details', {
itemId: Math.floor(Math.random() * 100),
})
}
/>
<Button title="Go to Home" onPress={() => navigation.navigate('Home')} />
<Button title="Go back" onPress={() => navigation.goBack()} />
</View>
);
}
const Stack = createNativeStackNavigator();
export default function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Details" component={DetailsScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}```

Related

Passing parameters to routes

I am currently fiddling with some exercise code, from what i seen in https://reactnavigation.org/docs/params/
You should be able to pass more than 1 params with route
But i can't seem to do that .
I only manage to send 1 of the two params that i wanted to pass from Topping.js to Rasa.js
What am i possibly doing wrong ?
Any help is appreciated
Topping.js
export default function HalTopping({route,navigation}){
const { JenisMie } = route.params;
const TipeMie = JenisMie;
return(
<ScrollView>
<Text>itemId: {JSON.stringify(JenisMie)}</Text>
<View style={styles.container}>
<View style={styles.card}>
<View style={styles.card_header}>
<Text style={styles.title}> Telur Dadar </Text>
</View>
<View style={{alignItems : 'center', margin : 20}}>
<Image
style={{width: 300, height : 300}}
source={require('./Img/Dadar.jpg')}
/>
</View>
</View>
<View style={styles.card_footer}>
<Button
title="Pilih!"
color="#dc3545"
onPress={() => navigation.navigate('HalPedas', {JenisTopping: "Telur Dadar"})} />
</View>
</View>
</ScrollView>
)
};
Rasa.js
export default function HalPedas({route,navigation}){
const { JenisMie1 } = route.params;
const { JenisTopping } = route.params;
return(
<Text>itemId1: {JSON.stringify(JenisMie1)}</Text>
<Text>itemId2: {JSON.stringify(JenisTopping)}</Text>)
App.js
import * as React from 'react';
import { Button, View, Text } from 'react-native';
import { useNavigation, NavigationContainer } from '#react-navigation/native';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
import HalTopping from './Topping';
import HalPedas from './Rasa';
import HalPesanan from './Pesanan';
const Stack = createNativeStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="HalTopping" component={HalTopping}/>
<Stack.Screen name="HalPedas" component={HalPedas}/>
<Stack.Screen name="HalPesanan" component={HalPesanan}/>
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;
When you navigate to 'HalPedas' you are only passing through one parameter, 'JenisTopping'.
<View style={styles.card_footer}>
<Button
title="Pilih!"
color="#dc3545"
onPress={() => navigation.navigate('HalPedas', {JenisTopping: "Telur Dadar"})}
/>
</View>
You can add an additional parameter as seen below
<View style={styles.card_footer}>
<Button
title="Pilih!"
color="#dc3545"
onPress={() => navigation.navigate('HalPedas', {
JenisTopping: "Telur Dadar",
JennisMeil: "Something Else"
})}
/>
</View>

OnbackPrees to return home always in react stack navigation

I am do do navigation in react native where all the back arrow or back press return to initial route. On last on option is to list to onBackPreessed event and passs call to init route which is home.
I am hoping their will be props for allowing the Screen to return to init Screen in stack navigations
What is happening
On home:
go details then go A
back arrow press in A, it return back to details
Need actions
On home:
go details then go A
back arrow press in A return back to home instead of details
The code I try
import * as React from 'react';
import { Button, View, Text } 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')}
/>
</View>
);
}
function DetailsScreen({ navigation }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Details Screen</Text>
<Button
title="Go to A"
onPress={() => navigation.navigate('A')}
/>
</View>
);
}
function A({ navigation }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>AAAAAAAAAAAAAAAAAAA Screen</Text>
</View>
);
}
const Stack = createNativeStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Home" detachInactiveScreens={true}
detachPreviousScreen={true}>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Group screenOptions={{ presentation: 'modal' }}>
<Stack.Screen name="Details" component={DetailsScreen}
options={{ presentation: 'transparentModal' }}
/>
<Stack.Screen name="A" component={A} />
</Stack.Group>
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;
u can do it by passing "key" to "navigate"
more info (source):
https://reactnavigation.org/docs/navigation-prop/
https://reactnavigation.org/docs/navigation-prop/#going-back-from-a-specific-screen
navigation.navigate({ name: SCREEN, key: SCREEN_KEY_A });
navigation.navigate({ name: SCREEN, key: SCREEN_KEY_B });
navigation.navigate({ name: SCREEN, key: SCREEN_KEY_C });
navigation.navigate({ name: SCREEN, key: SCREEN_KEY_D });
navigation.navigate({ key: SCREEN_KEY_A }); // will go to screen A FROM screen D
I think you can use BackHandler on Screen A.
So you should listen for BackHandler in Screen A and the navigate to Home screen when it's triggered.
Your Screen A should look like this:
import { BackHandler } from 'react-native';
function handleBackPressHandler() {
navigation.navigate('HomeScreen');
return true;
}
useEffect(() => {
BackHandler.addEventListener('hardwareBackPress', handleBackPressHandler);
return () => {
BackHandler.removeEventListener('hardwareBackPress', handleBackPressHandler);
};
}, []);
The default behaviour of React Navigation is this only, it takes you to the last visited stack on pressing back but if you want to update it, you can you this line of code:
useFocusEffect( //imported from #react-navigation/native-stack
React.useCallback(() => {
const onBackPress = () => {
navigation.navigate('InitialRouteName');
};
BackHandler.addEventListener('hardwareBackPress', onBackPress);
return () =>
BackHandler.removeEventListener('hardwareBackPress', onBackPress);
}, [])
);
For reference, you can check this out - https://reactnavigation.org/docs/custom-android-back-button-handling/
please try this,
import { BackHandler } from 'react-native';
<!- -->
useEffect(() => {
const backAction = () => {
navigation.navigate('intialRouteName');
return true;
};
const backHandler = BackHandler.addEventListener(
'hardwareBackPress',
backAction,
);
return () => backHandler.remove();
}, []);

How can I send text taken from user to another screen to display it in <text> in react native? (I am a beginner)

App.js
function App() {
const [getScreen, showScreen] = useState(false);
const [getEmail, setEmail] = useState("");
return (
<View>
<LoginScreen />
<LoginContexts.Provider
value={{ getEmail, setEmail, getScreen, showScreen }}
>
{showScreen ? <Screen2 /> : <LoginScreen />}
</LoginContexts.Provider>
</View>
);
}
export default App;
Login
function LoginScreen({ navigation }) {
const { getEmail, setEmail, showScreen } = useContext(LoginContexts);
function gotEmail(inputEmail) {
setEmail(inputEmail);
}
return (
<View style={styles.container}>
<Text style={styles.loginText}>Login</Text>
<View style={styles.textInput}>
<TextInput
placeholder="Please enter your email"
defaultValue={getEmail}
onChange={gotEmail}
/>
</View>
<View style={styles.space} />
<View style={styles.passwordStyle}>
<TextInput
placeholder="password"
secureTextEntry
autoCorrect={false}
autoCapitalize="none"
/>
</View>
<View style={styles.space} />
<View>
<Button
style={styles.loginBTN}
title="Login"
onPress={() => {
showScreen(true);
}}
/>
</View>
</View>
);
}
export default LoginScreen;
Screen 2
function Screen2() {
const { getEmail } = useContext(LoginContexts);
return (
<View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
<Text>{getEmail}</Text>;
</View>
);
}
export default Screen2;
LoginContext <-- used context api
import { createContext } from "react";
export const LoginContexts = createContext({});
Could you please tell me that why data is not going to another page?
I used useContext but I am not able to send data to another page. Please help me to solve this problem.
In this I had taken input from user as email and I want to display that email in text view in another page but I am unable to do that. On button click nothing happens.

In React Native Navigation, how do I send props to my screens?

I want to be able to use navigation on a different screen other than just the first one but I am getting an error that this.props does not exist.
I have my App.js file setup like this:
import { createStackNavigator } from '#react-navigation/stack';
import { NavigationContainer } from '#react-navigation/native';
import Screen2 from './screens/Screen2';
import Screen3 from './screens/Screen3';
import HomeScreen from './screens/HomeScreen';
const Stack = createStackNavigator();
function HomeScreen({ navigation }) {
return (
<View>
<Button
title="Go to Screen2"
onPress={() => {
navigation.navigate('Screen2');
}}
/>
<Button
title="Go to Screen3"
onPress={() => {
navigation.navigate('Screen3');
}}
/>
</View>
);
const App: () => React$Node = () => {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Screen2" component={Screen2} />
<Stack.Screen name="Screen3" component={Screen3} />
</Stack.Navigator>
</NavigationContainer>
);
};
The buttons in app.js work but if I go to Screen2 and click a button that intends to go to another (Screen3 in the example below), props does not exist.
Example Screen2.js would look like this:
const Screen2: () => React$Node = () => {
return (
<>
<View style={{ flex: 1 }}>
<Button
title="Go to Screen3"
onPress={goToScreen3}}
/>
</View>
</>
);
function goToScreen3() {
if(condition){
this.props.navigate.navigate('Screen3');
}}
How do I pass the props so that I can use navigation in my second screen?
For functional component sometimes it's tricky to pass navigation through props as well. So just use withNavigation.
you have to import it and wrap the function with it.
import { withNavigation } from 'react-navigation';
const Screen2 = props => {
const goToScreen3 = () => {
if(condition){
props.navigate.navigate('Screen3');
}}
return (
<>
<View style={{ flex: 1 }}>
<Button
title="Go to Screen3"
onPress={goToScreen3()}
/>
</View>
</>
);
export default withNavigation(Screen2)
In Functional Component there is no this binding so you need to get the props from the function first
check th
const Screen2 = (props) => {
return (
<>
<View style={{ flex: 1 }}>
<Button
title="Go to Screen3"
onPress={goToScreen3}}
/>
</View>
</>
);
function goToScreen3() {
if(condition){
props.navigate.navigate('Screen3');
}
}
}

Display buttons dependent on variable value in React Native

I am using the following code to display a 'Home' page with a button on it in React Native...it is functional without difficulty:
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 }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<Button title="Go to Login" onPress={() => navigation.navigate('Login')} />
</View>
);
}
function LoginScreen({ navigation }) {
//do things to login here
}
const Stack = createStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Login" component={LoginScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;
The problem arises when I try to modify the code to display a button on the 'Home' page dependent on the value of a global variable, I get an error. I am not sure why however it may be the 'HomeScreen' function does not recognize the value of the '_secured' variable...?
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';
var _secured = 0;
function HomeScreen({ navigation }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
if (_secured === 0) {
<Button title="Go to Login" onPress={() => navigation.navigate('Login')} />
} else {
<Button title="Stuff" onPress={() => navigation.navigate('DoStuff')} />
}
</View>
);
}
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="DoStuff" component={StuffScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;
Any suggestions greatly appreciated, I am new to React Native. I thank you in advance.
Unfortunately I am still having immense difficulty trying to figure this out, it is incredibly frustrating. I believe I need to define my 'global' variable using the 'useState'. My code for the 'Home' screen is as follows:
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="Stuff"> onPress={() => navigation.navigate('DoStuff')} </Button>)
}
As previously mentioned I am new to developing for React Native. The inability to use simple if/else statements to accomplish this is extremely disheartening. I thank anybody in advance for some insight.
Just like an ordinary function, react renderer cannot return more than one JSX element. So wrapping up your original code inside a single JSX EmptyView <></> and then using JS to evaluate conditions and finally returning a button view.
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="Stuff" onPress={() => navigation.navigate('DoStuff')} > </Button>)}
</>
);
}

Categories