How to modify/calculate a balance on different screens? - react-native

I want to have a balance account screen, which when a user withdraws or deposits, the balance account is modified accordingly. Sounds simple enough only problem is that I've just started learning react and google isn't being super helpful.
So far I have a BankBalance.js and several screens that I will use to modify the value, so below is the current code for BankBalance.js:
import React from "react";
import { Text } from "react-native";
import styles from "../components/styles";
var initBalance = 1903.54;
var amount = 0;
var finalBalance = initBalance + amount;
var BankBalance = () => {
return <Text style={styles.textMain}>£{finalBalance.toString()}</Text>;
};
export default BankBalance;
And an example from the deposit screen:
import React from "react";
import { useNavigation } from "#react-navigation/core";
import { Text, View, Image } from "react-native";
import { StatusBar } from "expo-status-bar";
import styles from "../components/styles";
import AppButton from "../components/AppButton";
import ExitBtn from "../components/ExitBtn";
import Keyboard from "../components/Keyboard";
function CDScreen(props) {
const navigation = useNavigation();
return (
<View style={styles.container}>
<StatusBar style="auto" />
<View style={styles.topBanner}>
<Text style={styles.topBanTxt}>Enter an amount to deposit</Text>
</View>
<View style={styles.container}>
<Image
resizeMode="contain"
source={require("../assets/cash-dep.png")}
/>
<Keyboard />
<AppButton
style={styles.textMain}
onPress={() => navigation.push("Receipt")}
title="Accept"
/>
</View>
<View style={styles.btmBanner}>
<ExitBtn
style={styles.btmBanTxt}
onPress={() => navigation.goBack()}
title="Go Back"
/>
</View>
</View>
);
}
export default CDScreen;
I'm probably going about this the wrong way so if anyone has pointers that would be really great.
Just in case Keyboard:
import React, { Component } from "react";
import { TextInput, StyleSheet, View } from "react-native";
import { Entypo } from "#expo/vector-icons";
import styles from "../components/styles";
class Keyboard extends Component {
constructor() {
super();
this.state = {
amount: "",
};
}
handleAmount(txt) {
this.setState({
amount: txt,
});
}
render() {
return (
<View style={keyStyles.keyContainer}>
<Entypo name="keyboard" size={35} color="black" />
<TextInput
keyboardType="numeric"
onChangeText={this.handleAmount.bind(this)}
value={this.state.amount}
style={styles.txtInput}
></TextInput>
</View>
);
}
}
const keyStyles = StyleSheet.create({
keyContainer: {
justifyContent: "center",
alignItems: "center",
alignContent: "center",
padding: 8,
},
});
export default Keyboard;
Thanks in advance :)

Redux You can translate a simple counter application given here. It can be a main balance, not initial 0. Accordingly, you can find a solution to the problem by triggering 'increment' when depositing money, and 'decrement' when withdrawing money.

In react the values of the components are not globally accessible. You will have to use something to store them and access them everywhere.
You can use Redux or Context for that

Related

Expo / TouchableOpacity onPress() not responding

I'm trying to reproduce a pomodoro app from an online course.
I've been looking at my code for several hours, going back and forth with the course, but can't find my error.
TouchableOpacity or Pressable used in RoundedButton component doesn't trigger onPress()
I tried different command to test if my logic with setStarted was flawe, without success.
Anyone can help me find my bug ?
Here is the link to the expo : https://snack.expo.dev/#battlepoap/focus-time
RoundedButton.js:
import React from 'react';
import { TouchableOpacity, Text, StyleSheet, View } from 'react-native';
export const RoundedButton = ({
style = {},
textStyle = {},
size = 125,
...props
}) => {
return (
<View>
<TouchableOpacity style={[styles(size).radius, style]}>
<Text style={[styles(size).text, textStyle]}>{props.title}</Text>
</TouchableOpacity>
</View>
);
};
const styles = (size) =>
StyleSheet.create({...});
Example with Focus.js where we add a task by pressing on the RoundedButton :
import React, { useState } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { TextInput } from 'react-native-paper';
import { RoundedButton } from '../../components/RoundedButton';
import { fontSizes, spacing } from '../../utils/sizes';
export const Focus = ({ addSubject }) => {
const [tempSubject, setTempSubject] = useState(null);
return (
<View style={styles.container}>
<View style={styles.titleContainer}>
<Text style={styles.title}>What do you want to focus on ?</Text>
<View style={styles.inputContainer}>
<TextInput
style={{ flex: 1, marginRight: spacing.sm }}
onSubmitEditing={({ nativeEvent }) => {
setTempSubject(nativeEvent.text);
}}
/>
<RoundedButton
size={50}
title="+"
onPress={() => addSubject = tempSubject}
/>
</View>
</View>
</View>
);
};
sic In the additional files there was ....
One thing we however need to add in order to make sure the button triggers is the onPress method. This method allows us to trigger the touch event of the user. Don't forget it!!
<TouchableOpacity style={[styles(size).radius, style]}>
<Text
style={[styles(size).text, textStyle]}
onPress={props.onPress}>
{props.title}
</Text>
</TouchableOpacity>

React Native element only visible/usable after pressing a button

New to React Native, having a go at an app idea. Basically I'm just trying to create an TextInput element that appears when I press a Button. Below is my attempt. I'm trying to take advantage of state within my class, but something is off.
Expo is throwing an error of 'null is not an object (evaluating 'this.state.isShowingText')'.
Any ideas?
import React, { Component } from 'react';
import { TextInput, Alert, Button, ScrollView, Text, View, StyleSheet } from 'react-native';
export default class CoolComponent extends Component {
render() {
const nameAdd = () =>{
state = { isShowingText: true };
}
return (
<View style={{ alignItems: 'center', top: 50 }}>
<Title>Some Title</Title>
{this.state.isShowingText ? <TextInput></TextInput> : null}
<ScrollView></ScrollView>
<Button
title="Press me"
onPress={nameAdd}
/>
</View>
);
}
}
The way you handling state is wrong
import React, { Component } from 'react';
import { TextInput, Button, ScrollView, View } from 'react-native';
export default class CoolComponent extends Component {
state = {
isShowingText: false
}
nameAdd = () => {
this.setState({
isShowingText: true
})
}
render() {
return (
<View style={{ alignItems: 'center', top: 50 }}>
{this.state.isShowingText ? <TextInput style={{ width: '50', height: '50', borderWidth: 1 }}></TextInput> : null}
<ScrollView></ScrollView>
<Button
title="Press me"
onPress={this.nameAdd}
/>
</View>
);
}
}
Hope this helps you. Feel free for doubts.

Image Slider implemented using Carousel is not working

I am working on an App which can display a simple Image Slider using Carousel.
I have used the Carousel from "react-native-banner-carousel" library.
Code:
ImageSlider.js
import React from 'react';
import Carousel from 'react-native-banner-carousel';
import { StyleSheet, Image, View, Dimensions } from 'react-native';
const BannerWidth = Dimensions.get('window').width;
const BannerHeight = 260;
const images = [
"https://images-na.ssl-images-amazon.com/images/I/61McsadO1OL.jpg",
"https://images-na.ssl-images-amazon.com/images/I/51vlGuX7%2BFL.jpg",
"https://images-na.ssl-images-amazon.com/images/I/717DWgRftmL._SX522_.jpg"
];
export default class ImageSlider extends React.Component {
renderPage(image, index) {
return (
<View key={index}>
<Image style={{ width: 500, height: BannerHeight }} source={{ uri: image }} />
</View>
);
}
render() {
return (
<View style={styles.container}>
<Carousel
autoplay
autoplayTimeout={5000}
loop
index={0}
pageSize={BannerWidth}
>
{images.map((image, index) => this.renderPage(image, index))}
</Carousel>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
justifyContent: 'center'
},
});
App.js
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import Header from './components/Header';
import ImageSlider from './components/ImageSlider';
class App extends Component {
render () {
return (
<View>
<Header headerText = "SAMPLE APP" />
<ImageSlider />
</View>
);
}
}
export default App;
I am importing ImageSlider inside the App.js
I am trying the method mentioned in this link: https://github.com/f111fei/react-native-banner-carousel
But the output I am getting is somewhat like this:
Where am I going wrong here?
class App extends Component {
render () {
return (
<View style={{flex:1}}>
<Header headerText = "SAMPLE APP" />
<ImageSlider />
</View>
);
}
}
Notice this in the above code
<View style={{flex:1}}>
Hope this will help.!

React navigation this.props.navigation undefined

I have a custom header like this
import React from 'react';
import { View, TouchableOpacity, Text, StyleSheet, Image } from 'react-native';
import { Header, Left, Right, } from 'native-base';
import { Icon } from 'react-native-elements';
export default class MainHeader extends React.Component {
pressSearch() {
this.props.navigation.navigate('Login');
}
render () {
return(
<Header style={{paddingTop:25}}>
<Left style={{marginBottom:10}}>
<TouchableOpacity>
<View style={{flexDirection:'row'}}>
<Image
style={styles.stretch}
source={require('../images/logoforplay.png')}
/>
<Text style={styles.headerText} > Eventlinn </Text>
</View>
</TouchableOpacity>
</Left>
<Right>
<TouchableOpacity
style={styles.headerButton}
onPress={this.pressSearch.bind(this)}
>
<Icon
name={'search'}
/>
</TouchableOpacity>
<TouchableOpacity
style={styles.headerButton}
>
<Icon
name={'add-location'}
/>
</TouchableOpacity>
<TouchableOpacity
style={styles.headerButton}
>
<Icon
name={'notifications'}
/>
</TouchableOpacity>
</Right>
</Header>
)
}
}
const styles = StyleSheet.create ({
mainContainer: {
flex:1,
backgroundColor:'white'
},
cardContainer: {
flex:1
},
stretch: {
height:35,
width:35,
},
headerText: {
fontSize:24,
marginTop:3,
},
headerButton: {
marginBottom:10,
marginLeft:15
}
})
My problem navigation.navigate not working.My routers working well because i can navigate to 'login' with another screen.I read something about pure components but still dont understand how to solve this problem.What do you suggest ? By the way i am new to react native.
If your header isn't a route within your Router at the head of your app you will need to use withRouter from react-router
import {withNavigation} from 'react-navigation'
export default withNavigation(MainHeader)
Now you should be able to access this.props.navigation without directly passing it down as a prop from a parent component.
use import { withNavigation } from 'react-navigation'; at the top and then export default withNavigation(FilmItem); at the end.
See doc : https://reactnavigation.org/docs/en/connecting-navigation-prop.html

How to add a NavigationDrawer in react native?

I know this question has been asked before, but for my situation I can't find an answer. I am helping make an app with a friend and I am tasked with making a DrawerNavigator for one of our screens. I am using react native for this.
Here is my render function inside the class of one of my screens
render() {
return (
<Container>
<Header title='BarMate'/>
<View style={styles.container}>
<MapView
style={{ alignSelf: 'stretch', height: 750}}
region={this.state.mapRegion}
onRegionChange={this._handleMapRegionChange}
/>
</View>
</Container>
);
}
The problem is that when I try to add an icon and button to the Header, it just doesn't show up. Here is the code after I added the icon
render() {
return (
<Container>
<Header title='BarMate'>
<Left>
<Icon name="ios-menu" onPress={() =>
this.props.navigation.navigate('DrawerOpen')} />
</Left>
</Header>
<View style={styles.container}>
<MapView
style={{ alignSelf: 'stretch', height: 750}}
region={this.state.mapRegion}
onRegionChange={this._handleMapRegionChange}
/>
</View>
</Container>
);
}
However, this code does work if instead of importing Container and Header from a custom made file like this:
import { Container } from '../components/Container'
import { Header } from '../components/Header'
I import them like this:
import {Container, Header, Icon, Button, Content, Left } from 'native-base'
I'm a beginner in react native so there might just be something here I'm overlooking, but any help would be appreciated. Here is what's in the files Container and Header my friend made.
//Header file
import React from 'react';
import { View, Text, StatusBar } from 'react-native';
import { Icon, Button, Content, Left} from 'native-base'
import styles from './styles';
const Header = ({title}) => (
<View style={styles.container}>
<StatusBar translucent={false} barStyle="light-content" />
<Text style={styles.title}>{title}</Text>
</View>
);
export default Header;
//Container file
import React from 'react';
import PropTypes from 'prop-types'; // ES6
import { View } from 'react-native';
import styles from './styles';
const Container = ({ children }) => (
<View style={styles.container}>
{children}
</View>
);
Container.propTypes = {
children: PropTypes.any,
}
export default Container;