I put console.log('Hello') to my button, to testing my button is work or not (actualy im using this button for navigation), but when i try to reload my app, my console show Hello. I didn't press my button yet, but when i try to press it my console didn't show hello.
Sorry for my bad english
import React from 'react';
import {View, TouchableOpacity, Image} from 'react-native';
import s from './SFooter';
import {useNavigation} from '#react-navigation/native';
const Footer = () => {
const navigation = useNavigation();
let active = 0;
return (
<View style={s.footerWrapper}>
<View style={s.iconsWrapper}>
<View style={s.iconWrapper}>
<TouchableOpacity
onPress={(console.log('asda'), () => navigation.navigate('Home'))}>
<Image
style={s.icon}
source={require('../../assets/icon/home.png')}
/>
{active == 0 ? <View style={s.iconActive} /> : <View />}
</TouchableOpacity>
</View>
<View style={s.iconWrapper}>
<TouchableOpacity>
<Image
style={s.icon}
source={require('../../assets/icon/book.png')}
/>
{active == 1 ? <View style={s.iconActive} /> : <View />}
</TouchableOpacity>
</View>
<View style={s.iconWrapper}>
<TouchableOpacity>
<Image
style={s.icon}
source={require('../../assets/icon/newspaper.png')}
/>
{active == 2 ? <View style={s.iconActive} /> : <View />}
</TouchableOpacity>
</View>
<View style={s.iconWrapper}>
<TouchableOpacity>
<Image
style={s.icon}
source={require('../../assets/icon/user.png')}
/>
{active == 3 ? <View style={s.iconActive} /> : <View />}
</TouchableOpacity>
</View>
</View>
</View>
);
};
export default Footer;
Please do check your code twice. You cannot call any function directly onPress. what i mean to say is following
Wrong:
<TouchableOpacity
onPress={(console.log('asda'), () => navigation.navigate('Home'))}
Correct
<TouchableOpacity
onPress={() => (console.log('asda'), () => navigation.navigate('Home'))}>
Related
I'm new to react native, trying to write a small project (notebook). I implemented the buttons, they all work, but when I save an entry to the form, nothing is displayed and does not give errors.
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Modal, Text, View, ScrollView, TextInput, Image, Button } from 'react-native';
import { Ionicons } from '#expo/vector-icons';
import React, {useState} from 'react';
import { Formik } from 'formik';
export default function App() {
const [news, setnews] = useState([
{name: '', text: ''}
]);
const addArtical = (artical) => {
setnews((list) => {
artical.key = Math.random().toString();
return[
artical,
...list
]
});
setModalWindow(false);
}
const [modalWindow, setModalWindow] = useState(false);
return (
<View style={styles.container}>
<Text style={styles.title}>Main tasks:</Text>
<ScrollView horizontal={true} showsHorizontalScrollIndicator={false}>
<View style={styles.up}>
<View style={styles.cub}></View>
<View style={styles.cub}></View>
<View style={styles.cub}></View>
<View style={styles.cub}></View>
<View style={styles.cub}></View>
<View style={styles.cub}></View>
</View>
</ScrollView>
<ScrollView vertical={true} showsVerticalScrollIndicator={false}>
<View style={styles.all}>
<TextInput style={styles.d} placeholder=' Search'></TextInput>
<Text style={styles.titletwo}>Other tasks:</Text>
<Ionicons style={styles.ic} name="add" size={30} color="black" onPress={() => setModalWindow(true)}/>
</View>
<Modal visible={modalWindow}>
<Ionicons style={styles.ic} name="close" size={30} color="black" onPress={() => setModalWindow(false)}/>
<View>
<Formik initialValues={{name: '', text: ''}} onSubmit={(values, clean) => {
addArtical(values);
clean.resetForm();
}}>
{(props) => (
<View >
<TextInput value={props.values.name} placeholder='Name' onChangeText={props.handleChange('name')}/>
<TextInput value={props.values.text} multiline placeholder='Text' onChangeText={props.handleChange('text')}/>
<Button title='Add' onPress={props.handleSubmit}/>
</View>
)}
</Formik>
</View>
</Modal>
</ScrollView>
</View>
);
}
Read more: I click add entry, a field opens with the addition of text, fill in the field with the necessary information, save, everything is successful, but my entry is nowhere
I am implementing my own Modal, trying to replace the Alert.alert with something more beautiful. I made it to be displayed when needed, but it is not hiding on the button press, but I think I transferred it the needed function. My modal structure is the following:
export const RCModal = ({ title, visible, onButtonPress }) => {
return (
<Modal
animationType='fade'
transparent={true}
visible={visible}
>
<View style={styles.container}>
<Text style={styles.title}>{title}</Text>
<Pressable style={styles.button} onPress={onButtonPress}>
<Text style={styles.text}>OK</Text>
</Pressable>
</View>
</Modal>
)
};
And it is used in the application in the following way:
// ...
const [alertVisible, setAlertVisible] = useState(false);
const [alertTitle, setAlertTitle] = useState();
const [alertOnPress, setAlertOnPress] = useState();
// ...
const winner = (theWinner) => {
setBlocked(true);
setAlertTitle(`${theWinner} win!`);
setAlertOnPress(() => setAlertVisible(!alertVisible));
setAlertVisible(true);
}
// ...
return (
<View style={styles.container}>
<RCModal title={alertTitle} visible={alertVisible} onButtonPress={alertOnPress} />
<ScrollView contentContainerStyle={{ flexGrow: 1, justifyContent: 'center' }}>
<Text style={styles.title}>Noughts and Crosses</Text>
<Text style={styles.tip}>Get {winCondition()} in row, column or diagonal</Text>
<View style={styles.buttonsContainer}>
<Text style={styles.turnContainer}>Turn: <Text style={[styles.turn, { color: turn === 'X' ? '#2E86C1' : '#E74C3C'}]}>{turn}</Text></Text>
<TouchableHighlight underlayColor="#000000" style={[styles.button, styles.newGameButton]} onPress={setInitialFieldState}>
<Text style={styles.buttonText}>New game</Text>
</TouchableHighlight>
</View>
<Field state={fieldState} size={fieldSize} onCellPress={onCellPress} />
</ScrollView>
<View style={styles.settingsButtonContainer}>
<TouchableHighlight underlayColor={theme.colors.secondary} style={styles.settingsButton} onPress={onSettingsPress}>
<Image source={require('../img/settings.png')} style={styles.settingsIcon} />
</TouchableHighlight>
</View>
</View>
);
};
When the winner() is called, it is displayed as it should, but when I press OK button, it is not hiding. How can I fix it?
You can use setAlertVisible to change the alertVisible state:
<RCModal title={alertTitle} visible={alertVisible} onButtonPress={() => setAlertVisible(false)} />
The answer was that to set a function like a state variable, I needed to set it like
setAlertOnPress(() => () => setAlertVisible(false))
(2 x () =>)
When I click on Sign Up button I want to navigate to Sign up page but it did not work. I have imported the screens and navigated screen also to app.js file. I am getting an ReferenceError : Can't find variable: navigation. Also I am unable to insert background image? Below is the Sign Up page.
import React from 'react';
import { StyleSheet,ImageBackground,Text, View, TextInput, TouchableOpacity } from 'react-native';
let bgImage='../../resources/images/bg2.png'
export default class LoginScreen extends React.Component {
state={
email:"",
password:"",
}
render(){
return (
<View style={styles.container}>
<Text style={styles.logo}>Trollo</Text>
<View style={styles.box}>
<View style={styles.inputView} >
<TextInput
style={styles.inputText}
placeholder="Email"
placeholderTextColor="#808080"
onChangeText={text => this.setState({email:text})}/>
</View>
<View style={styles.inputView} >
<TextInput
secureTextEntry
style={styles.inputText}
placeholder="Password"
placeholderTextColor="#808080"
onChangeText={text => this.setState({password:text})}/>
</View>
<TouchableOpacity style={styles.loginBtn}>
<Text style={styles.loginText}>SIGN IN</Text>
</TouchableOpacity>
<TouchableOpacity>
<Text style={styles.forgot}>Forgot Password?</Text>
</TouchableOpacity>
</View>
<Text style={styles.text1}>New Here?</Text>
<TouchableOpacity style={styles.signupBtn} onPress = {(navigation) => navigation.navigate('Sign Up')}>
<Text style={styles.loginText}>SIGN UP</Text>
</TouchableOpacity>
<Text style={styles.logoText}>Trollo</Text>
</View>
);
}
}
});
onPress handler does not getting called with navigation as the first parameter. That is undefined. navigation is a prop to your class component which is provided by stack navigator setup.
Instead of
onPress = {(navigation) => navigation.navigate('Sign Up')}
use
onPress = {() => this.props.navigation.navigate('Sign Up')}
I am trying to load data from Async Storage in react-native. I managed to load all User Data from API to async storage and I was able to display it in UserData(), however when I try to return received data to other components I get:
[Unhandled promise rejection: SyntaxError: JSON Parse error: Unexpected identifier "undefined"]
I assumed data is returned asyncroniously so I tried to await it however then I was getting:
[Unhandled promise rejection: Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:]
I searched this error and all I found out was that it assumes I was calling hooks in class. It is not truth however, because I simply used setState() in UserProfile() to save data received from UserData(). Could anyone please tell me what am I doing wrong? Thanks for all the help in advance.
Function I used to retrieve user data from:
import React, { useState } from "react";
import { View, Text } from "react-native";
import storage from "./Storage";
export default function UserData() {
const [userData, setuserData] = useState();
storage
.load({
key: "user",
autoSync: true,
syncInBackground: true,
})
.then(ret => {
setuserData(JSON.stringify(ret.info));
})
.catch(err => {
// console.warn(err.message);
return;
});
if (userData) return userData;
}
Function which displays user profile:
import React, { useState, useEffect } from "react";
import DeleteUser from "./DeleteProfile";
import PayPal from "../navigation/PayPal";
import { Button, TextInput, Text, ScrollView, View, Image } from "react-native";
import Styles from "../../styles/Styles";
import storage from "../elements/Storage";
import UserData from "../elements/GetUserData";
export default function UserProfile() {
const [email, setEmail] = useState("");
const [name, setName] = useState("");
const [phone, setPhone] = useState("");
const [premium, setpremium] = useState(false);
const [admin, setAdmin] = useState(false);
const [id, setId] = useState("");
const [checkout, setCheckout] = useState(false);
const info = UserData();
useEffect(() => {
async function getData() {
const result = JSON.parse(info);
setEmail(result.email);
setName(result.name);
setId(result._id);
setPhone(result.phone);
setpremium(result.premium);
setAdmin(result.admin);
}
getData();
}, []);
return (
<ScrollView style={Styles.userProfile}>
<View style={(Styles.bigBar, { textAlign: "center" })}>
<Text style={Styles.h1}>Profile Page</Text>
</View>
<View style={Styles.profileContent}>
<View>
<Image
style={Styles.profileImg}
source={{
uri: "https://i.pinimg.com/736x/8b/16/7a/8b167af653c2399dd93b952a48740620.jpg",
}}
/>
</View>
<View>
<View>
<View style={Styles.profileView}>
<Text style={Styles.h6}>User name: </Text>
</View>
</View>
<View>
<View style={Styles.profileView}>
<Text style={Styles.h6}>Email: </Text>
</View>
</View>
<View>
<View style={Styles.profileView}>
<Text style={Styles.h6}>Phone number: </Text>
</View>
</View>
<View>
{/* {premium && ( */}
<View style={Styles.profileView}>
<Text style={Styles.h6}>premium: </Text>
</View>
{/* )} */}
</View>
<View>
{/* {!premium && ( */}
<View style={Styles.profileView}>
<Text style={Styles.h6}> premium: </Text>
<View
style={{
color: "red",
}}
></View>
</View>
{/* )} */}
</View>
{/* {admin && ( */}
<View style={Styles.profileView}>
<Text style={Styles.h6}>Admin: </Text>
<View style={{ color: "green" }}></View>
</View>
{/* )} */}
</View>
<View>
<View>
<View style={Styles.profileView2}>
<Text style={Styles.h6}>{name}</Text>
</View>
</View>
<View>
<View style={Styles.profileView2}>
<Text style={Styles.h6}>{email}</Text>
</View>
</View>
<View>
<View style={Styles.profileView2}>
<Text style={Styles.h6}>{phone}</Text>
</View>
</View>
<View>
{/* {premium && ( */}
<View style={Styles.profileView2}>
<View style={{ color: "orange" }}>
<Text style={Styles.h6}> POSIADANE</Text>
</View>
<View style={{ marginBottom: 1 }} />
</View>
{/* )} */}
</View>
<View>
{/* {!premium && ( */}
<View style={Styles.profileView2}>
<View
className="inline"
style={{
color: "red",
}}
>
{checkout ? (
<View style={{ margin: 0 }}>
<PayPal />
</View>
) : (
<View style={Styles.smlBtn}>
<Button
style={{ marginLeft: 1, marginBottom: 1 }}
onPress={() => setCheckout(true)}
title="BUY PREMIUM"
/>
</View>
)}
</View>
</View>
{/* )} */}
</View>
{/* {admin && ( */}
<View style={Styles.profileView2}>
<View style={{ color: "green" }}>
<Text style={Styles.h6}> TRUE</Text>
</View>
</View>
{/* )} */}
</View>
</View>
<View>
{/* <DeleteUser id={id} /> */}
{/* <Link
className="rf update better"
to={{
pathname: `/editProfile/?${id}`,
}}
>
UPDATE
</Link> */}
</View>
</ScrollView>
);
}
Okay I figured it out. In order to execute it properly I had to handle Promise returned from UserData() with then. It looks like this in the end:
useEffect(() => {
async function getData() {
await UserData().then(result => {
setEmail(result.email);
setName(result.name);
setId(result._id);
setPhone(result.phone);
setpremium(result.premium);
setAdmin(result.admin);
});
}
getData();
}, []);
I am trying to navigate screens by pressing on specific images on SearchScreen.js. Each image leads to a different screen. I am currently trying navigate from the first image to the screen meo_sw.js. However, I am not being able to do so and I don't undersand why. Here is the code of SearchScreen.js :
import React from 'react';
import { ScrollView, StyleSheet, TextInput, Text, View, Image, TouchableOpacity} from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
function SearchScreen() {
return (
<View style={styles.screen}>
<View style={styles.container}>
<TextInput style={styles.inputBox}
underlineColorAndroid='rgba(0,0,0,0)'
placeholder="Procura aqui"
placeholderTextColor = "black"
selectionColor="black"
keyboardType="default"/>
</View>
<View style={styles.teste}>
<Text style={styles.festivais}>Recomendados</Text>
<ScrollView horizontal={true} showsHorizontalScrollIndicator={false} style={styles.festivais_lista}>
<TouchableOpacity>
<Image source={require('../assets/images/meo_sudoeste.png')} style={styles.image} onPress={() => navigation.navigate('meo_sw')}/>
</TouchableOpacity>
<TouchableOpacity>
<Image source={require('../assets/images/vodafone_coura.png')} style={styles.image} onPress={() => {}}/>
</TouchableOpacity>
<TouchableOpacity>
<Image source={require('../assets/images/superbock_superrock.png')} style={styles.image} onPress={() => {}}/>
</TouchableOpacity>
<TouchableOpacity>
<Image source={require('../assets/images/nos_primavera.png')} style={styles.image} onPress={() => {}}/>
</TouchableOpacity>
<TouchableOpacity>
<Image source={require('../assets/images/rock_in_rio.png')} style={styles.image} onPress={() => {}}/>
</TouchableOpacity>
<TouchableOpacity>
<Image source={require('../assets/images/edp_cooljazz.png')} style={styles.image} onPress={() => {}}/>
</TouchableOpacity>
</ScrollView>
</View>
</View>
);
}
SearchScreen.navigationOptions = {
title: 'Procurar',
};
const styles = StyleSheet.create({
//I took this part off because it is useless for this especific question
});
export default SearchScreen;
And here is the screen 'meo_sw.js':
import React from 'react';
import {View, Text, TouchableOpacity, StyleSheet} from 'react-native';
const meo_sw = props => {
return(
<View style={styles.header}>
<Text style={styles.texto}>Meo Sudoeste</Text>
</View>
)
};
const styles=StyleSheet.create({
header:{
width:'100%',
height:90,
paddingTop:36,
backgroundColor: 'blue',
alignItems: 'center',
justifyContent: 'center'
},
texto:{
color:'white',
fontSize: 18
}
})
export default meo_sw;
Please help me
What I would suggest is wrapping the Image in TouchableWithoutFeedback and then adding the onPress on the TouchableWithoutFeedback. https://facebook.github.io/react-native/docs/touchablewithoutfeedback
use hookrouter instead, the modern alternative to react-router: https://www.npmjs.com/package/hookrouter
...
import { useRoutes, usePath, A} from "hookrouter";
navigate('/about');
to answer OP question about navigating from image click:
...
<TouchableOpacity>
<Image source={require('../assets/images/meo_sudoeste.png')} style={styles.image} onPress={() => navigate('/meo_sw')}/>
</TouchableOpacity>
...
You should add:
function xx({navigation}) {}
It worked for me at least!
I think there could be these issues
First pass the navigation in the function searchScreen({navigation}).
Then there is no onPress prop available in <Image> component so use onPress on <TouchableOpacity>.