Using states in react native - ios

I'm pretty new to the idea of states in react native and have trouble using them to change the states of the components. I have three text components one which is a question and another two are answers (yes and no), and another text component that checks if my answer to the question is write, so the check text component. When I click on yes for a certain question the state of the last check component should change to 'right' if the answer was yes or to 'wrong' if the answer is no. So basically, this is what I want to do :
So, the idea is when i click on yes and then check the pop-up should be this. This is the code I have so far:
import React, {useState} from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
export default function App() {
const [myState, setMyState] = useState('Yes');
const [myState2, setMyState2] = useState('Right');
const updateState = () => {
let tempStr = myState;
if (tempStr == "Yes"){
setMyState2('Right');
}
else{
setMyState2('Wrong');
};
}
return (
<View style={{alignItems: 'center', top: 150}}>
<Text>Is the earth round?</Text>
<Text mystate={setMyState}>Yes</Text>
<Text mystate={setMyState}>No</Text>
<Text mystate2={setMyState2}>Check</Text>
</View>
);
}
Currently, none of my text components seem to work.
Can anyone tell me how it could be done. Thanks!

I believe this will sufficiently help you with your question. useEffect is basically the new ComponentWillUpdate for hooks, and you should use it to check for when a state in a functional component updates. On the other hand, your code wasn't working because you were passing a mystate prop to the Text component. There is simply no mystate prop, and there also isn't a command to tell the app that you are pressing the text. You can simply use the onPress prop. Personally I prefer using a TouchableOpacity, but you could use a Button or even just pass it into the Text component itself.
import React, { useState, useEffect } from 'react'
import { View, Text, TouchableOpacity, Alert } from 'react-native'
export default function App() {
const [myAnswer, setMyAnswer] = useState('Who knows')
const [correct, setCorrect] = useState('')
useEffect(() => {
if (myAnswer == 'Who knows') setCorrect('Please answer!')
else if (myAnswer == 'Round') setCorrect('Correct!')
else if (myAnswer == 'Not round') setCorrect('Wrong :(')
}, [myAnswer])
return (
<View style = {{ justifyContent: 'center', alignItems: 'center', flex: 1 }}>
<Text>Is the Earth round?</Text>
<TouchableOpacity
onPress = {() => setMyAnswer('Round')}>
<Text>Yes</Text>
</TouchableOpacity>
<TouchableOpacity
onPress = {() => setMyAnswer('Not round')}>
<Text>Nope</Text>
</TouchableOpacity>
<TouchableOpacity
onPress = {() => { Alert('Your answer was...', correct) }}>
<Text>Check My Answer</Text>
</TouchableOpacity>
</View>
)

Related

React Native functional components - Navigate between different screens, each on a separate .js file

In my functional-component-based React Native app, I want to navigate between different screens, each of which resides in a separate .js file. I want to be able to navigate multiple layers deep like this:
[Screen1.js] <-> [Screen2.js] <-> [Screen3.js] <-> [Screen4.js]
For some reason, the examples in the tutorial place all the screens within the same App.js file, each as their own separate function, which I would imagine is unusual developer behavior.
I would prefer to have the navigation stack in a single NavigationService.js file, which is then imported by each Screen#.js file. How could I implement this? (I've seen several SO answers on this, along with some online tutorials, but seemingly most of them implement class components instead of functional.)
Below is my attempt at implementing this environment, but when I try to navigate to a new screen, I get _NavigationService.default.navigate is not a function. (In '_NavigationService.default.navigate('Email')', '_NavigationService.default.navigate' is undefined).
NavigationService.js:
import * as React from 'react';
import { NavigationContainer } from '#react-navigation/native';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
import EmailScreen from './Email';
import HomeScreen from './App';
const Stack = createNativeStackNavigator();
function NavigationService( navigation ) {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Camera" component={CameraScreen} />
<Stack.Screen name="Email" component={EmailScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default {navigation, NavigationService};
App.js (HomeScreen):
import * as React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { Button } from 'react-native-elements';
import NavigationService from './NavigationService';
function HomeScreen() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: 'white' }}>
<Button buttonStyle={styles.cameraButton} titleStyle={styles.buttonText}
onPress={() => NavigationService.navigate('Email')}
title="Email pics"
/>
</View>
);
}
const styles = StyleSheet.create({
cameraButton: {
backgroundColor: 'red',
},
buttonText: {
fontSize: 24
}
});
export default HomeScreen;
Email.js (EmailScreen):
import * as React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import RNSmtpMailer from 'react-native-smtp-mailer';
function EmailScreen() {
return(
<View>
<Text>Test hi hi hi</Text>
</View>
)
}
export default EmailScreen;
You don't have to import your NavigationService in your individual screens. React Navigation takes care of that and injects a navigation property that you can use instead.
Use e.g.
function HomeScreen({ navigation }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: 'white' }}>
<Button buttonStyle={styles.cameraButton} titleStyle={styles.buttonText}
onPress={() => navigation.navigate('Email')}
title="Email pics"
/>
</View>
);
}
Your NavigationService would only be used somewhere in your entrypoint to render the stack navigator, and I suggest to rename it to avoid the misconception that it could be passed around as a service. It's simply a component in your app's hierarchy which establishes the navigation stack, and React Navigation ensures that the stack screens get the necessary properties like navigation or route (e.g. to fetch navigation parameters from).
For that reason, you also don't have to pass a navigation property into your NavigationService.
Here is a great tutorial with functional components distributed over multiple files.

ReactNative: Dismiss Keyboard on scroll of Multiline TextInput

I'm using a multiline TextInput and I would like to dismiss the keyboard while scrolling using the onScroll() props
The Code I tried:
<View>
<TextInput
onChangeText={(bodyContent) => this.setState({bodyContent})}
value = {this.state.bodyContent}
editable = {true}
multiline={true}
onScroll = {() => Keyboard.dismiss() }
/>
</View>
Also noticed that onScroll events don't get fired on a scroll (even tried with console.log( ) )
react-native": "0.57.3"
Platform: IOS
You are right, the onScroll is not firing. There is an issue about this topic, however because the person who created the issue used an out of date version of RN, the issue was closed. You should open a new issue with the newest release of RN. I used RN 0.59 so its definitely still an issue.
Link to issue: https://github.com/facebook/react-native/issues/20309
Here is my implementation that can be copied and pasted anywhere:
import React, { useState } from 'react';
import { StyleSheet, TextInput, View, Keyboard } from 'react-native';
const FormInput = () => {
const [text, setText] = useState();
return (
<View style={styles.container}>
<TextInput
onChangeText={setText}
value={text}
editable
multiline
onScroll={() => Keyboard.dismiss()}
style={{ flex: 1, backgroundColor: 'red' }}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1
}
});
export default FormInput;

Why we use the progressImage property in the ProgressViewIOS component in react-native?

Why and how to use the progressImage property in the <ProgressViewIOS/> component in react-native ? The documentation doesn't seem to be understandable. Can anyone share a screenshot output of this property on the iOS? Thanks !!!
progressImage is an image to use for the portion of the progress bar that is filled in ProgressViewIOS.
If you provide a custom image for it, the progressTintColor property is ignored.
Images:
progressImage.png
trackImage.png
Output:
Code:
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, ProgressViewIOS, Dimensions} from 'react-native';
const screenWidth = Dimensions.get("screen").width;
type Props = {};
export default class App extends Component<Props> {
render() {
return (
<View style={styles.container}>
<ProgressViewIOS
style={{width: screenWidth - 30}}
progress={0.5}
progressViewStyle = 'default'
trackImage={require('./trackImage.png')}
progressImage={require('./progressImage.png')}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});

differents buttons, differents images? react native

I'm a student and I developing a mobile app with React Native.
My target is this image:
(https://cdn.discordapp.com/attachments/403580119714889736/407172407049060352/Apercu_bingo_2_choisir_invites.jpg)
I could write the code with independent buttons, the problem appears when I want to add different images to each button. (I'm waiting for the back dev to create a boucle to add all the images with the shortest code possible (looking forward for some loop ideas ;) ).
import React, {Component} from 'react';
import Button from 'react-native-button';
import
{
AppRegistry,
StyleSheet,
View,
Text,
TouchableHighlight,
Alert,
Image,
ScrollView,
TouchableWithoutFeedback
}
from 'react-native';
import styles from './Styles';
class ToggleButton extends React.Component {
render() {
return (
<View style={styles.cont2}>
<TouchableHighlight style={styles.bubblechoice} onPress={this.props.onPress}>
<View style={[styles.overlay, this.props.selected ? {backgroundColor: '#3C1088'} : {}]}>
<Image style={styles.bubblechoice} source={require('./photo1.jpg')}/>
</View>
</TouchableHighlight>
</View>
);
}
}
export default class MyComponent extends Component
{
constructor(props) {
super(props);
this.state = {
inv1: false,
inv2: false,
};
}
updateChoice(type) {
let newState = {...this.state};
newState[type] = !newState[type];
this.setState(newState);
}
render() {
return (
<View style={styles.containerinvite}>
<ScrollView contentContainerStyle={styles.list}>
<ToggleButton label='inv1' onPress={() => { this.updateChoice('inv1') } } selected={this.state.inv1}/>
<ToggleButton label='inv2' onPress={() => { this.updateChoice('inv2') } } selected={this.state.inv2}/>
<TouchableWithoutFeedback
onPress={() => {Alert.alert('OK');}}>
<View style={styles.button}>
<Text style={styles.buttonText}>ok</Text>
</View>
</TouchableWithoutFeedback>
</View>
);
}
onPress1 = () => {
this.setState({
inv1: !this.state.inv1
});
}
onPress2 = () => {
this.setState({
inv2: !this.state.inv2
});
}
}
The result that I have is:
https://scontent-cdt1-1.xx.fbcdn.net/v/t35.0-12/28580783_10216099091730046_1132055272_o.png?oh=fdb33bbe2b82f29cac1d80b8e25f269e&oe=5A9B2488&dl=1, https://www.facebook.com/
The thing is that the View that changes the status color can't be without children, so I can't just change the image from there. I tried different options but I'm still can manage different photos with independents buttons.
From your parent component you should pass your photos to the child component and use that prop for your source instead of
<Image style={styles.bubblechoice} source={require('./photo1.jpg')}/> =>> This is wrong.
<Image style={styles.bubblechoice} source={require(photoUrls)}/> =>> It should be like this.
If you have further questions about it do not hesitate to ask.

Super expression must either be null or a function, react native 0.26.3

I am a newbie in react native.
I have one similar problem in different projects. When I try to compile my project, I see this problem. Why this error is appear?
P.S. I am learning react-native by tutorials like a appcoda.com
Picture of my error
Featured.js
'use strict';
var React = require('react-native');
var{
StyleSheet,
View,
Text,
Component
} = React;
var styles = StyleSheet.create({
description:{
fontSize: 20,
backgroundColor: 'white'
},
container:{
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
});
class Featured extends Component{
render() {
return(
<View style = {styles.container}>
<Text style = {styles.description}>
Featured tab
</Text>
</View>
);
}
}
module.exports = Featured;
Change your import statement as below
import React, { Component } from 'react';
import {
StyleSheet,
View,
Text,
} from 'react-native';

Resources