React Native element only visible/usable after pressing a button - react-native

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.

Related

How to modify/calculate a balance on different screens?

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

Undefined '_this2.props.navigation.navigate'

I have problems, i want to navigate to register from login in Modal. how solved this problem?
how so I can navigate in the Modal?
enter image description here
enter image description here
import React, { Component } from 'react';
import { Alert, StyleSheet, Text, TouchableOpacity, View, Dimensions, TextInput } from 'react-native';
import Modal from 'react-native-modalbox';
import Lock from '../../../assets/icon/lock.svg';
import User from '../../../assets/icon/user.svg';
var screen = Dimensions.get('window');
class Login extends Component {
constructor(props) {
super(props);
}
showLogin = () => {
this.refs.myLogin.open();
}
closeLogin = () => {
this.refs.myLogin.close();
}
render() {
return (
<Modal
ref={"myLogin"}
style={{
borderRadius: 10,
width: screen.width - 80,
shadowRadius: 10,
height: 300,
}}
position='center'
backdrop={true}
/>
)
}
}
and this button
<TouchableOpacity onPress={() => this.props.navigation.navigate('Register')}>
<Text style={{ color: '#024379', fontWeight: 'bold' }}>Daftar Disini</Text>
</TouchableOpacity>
Use withNavigation HOC to be able to access navigation prop in your component.
For reference see this

React Native code explanation

I have a simple app application project that I would appreciate if someone would explain the logic behind the code.
On the click on the button the text that is inside the text input appears on the imageBackground.
FilterView.js:
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
Image,
Button, Platform, TouchableOpacity, TextInput, ImageBackground } from 'react-native';
import { captureRef } from "react-native-view-shot";
import { Input } from 'react-native-elements';
import DynamicText from './DynamicText';
export default class FilterView extends Component {
constructor(props) {
super(props);
this.state = {
text: '',
imageURI: 'https://reactnativecode.com/wp-content/uploads/2018/02/motorcycle.jpg',
}
}
captureScreenFunction = () => {
captureRef({
format: "jpg",
quality: 0.8
})
.then(
uri => this.setState({ imageURI: uri }),
error => console.error("Oops, Something Went Wrong", error)
);
}
onTextReceived = (text) => {
this.setState({text});
}
render() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Button title="Capture Device Screenshot" onPress={this.captureScreenFunction} />
<ImageBackground source={{uri: this.state.imageURI}} style={{
width: 200,
height: 300,
marginTop: 5,
alignItems: 'center',
justifyContent: 'center'
}}>
<Text style={{color: 'white'}}>{this.state.text}</Text>
</ImageBackground>
<View style={{ flexDirection: 'row', justifyContent: 'space-around' }}>
<View>
<DynamicText onChangeText={this.onTextReceived}/>
</View>
</View>
</View>
);
}
}
DynamicText.js:
import React, { Component } from 'react';
import { StyleSheet, Text, View, Image, Button, Platform, TouchableOpacity, TextInput, ImageBackground } from 'react-native';
export default class DynamicText extends Component {
constructor(props) {
super(props);
this.state = {
text: '',
mode: 1 // 1 = edit, 2 = view
}
}
onChange = (text) => {
this.setState({text});
this.props.onChangeText(text);
}
render() {
return (
<View ref="dymanicView">
<TextInput
ref="newItemText"
style={{ height: 40 }}
placeholder="Type something..."
onChangeText={(text) => this.onChange(text)}
/>
</View>
)
}
}
DynamicText.defaultProps = {
onChangeText: () => {}
}
I would like to understand about the defaultProps. For instance what does it do and when can I use it. Also please explain step by step the order of defining and transferring data between the components.
First of all, stackoverflow is not a platform for this type of question. You have to understand first by yourself and then still you have any doubt then put it with code. Anyways I'll explain how it will call when you run your project.
step-1:
first of all FilterView.js is loaded then load everything which you wrote in import tag and in render function.
step-2
then this.state is mutable. This means that state can be updated in the future while props can't. we can initialize state in the constructor, and then call setState when we want to change it.
step-3
then render method call which display what you want/write.
step-4
then captureScreenFunction is a function which you have to call onPress event of Button and onTextReceived is also a function which is call on onTextChange method.
function can bind in different ways but here captureScreenFunction is bind like this captureScreenFunction = () => {} or you can bind like this this.captureScreenFunction = this.captureScreenFunction.bind(this);
step-4
DynamicText.js file get data using this.props which is write in this file. In this file onChange = (text) => {} which calls onChangeText() function which is wrote inside FilterView.js using this.props.
and at last for default.props I'm giving you a link please refer this.
defaultProps in React Native?
Hope it will help you.

Can't find variable: Button - React Native

I am trying to create a simple app with a button in react native, but so far every time I run my code, it gives me an error saying "Can't find variable: Button". I would like to end up with my title at the top (Already done) and a button in the center of the screen, which gives an alert when touched.
I have run through several online tutorials and cannot find a solution.
Here is my code:
/**
* Sample React Native App
* https://github.com/facebook/react-native
* #flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
class Project extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.Title}>
Lucas's App
</Text>
<View style={styles.buttonContainer}>
<Button
onPress={() => { Alert.alert('You tapped the button!')}}
title="Press Me"
/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
},
Title: {
color: '#000000',
marginTop: 13,
paddingLeft:100,
paddingRight:100,
fontFamily: 'Avenir',
fontSize: 30,
},
buttonContainer: {
margin: 20
},
});
AppRegistry.registerComponent('Project', () => Project);
Thanks in advance.
You need to make sure to import the button.
You can do this by adding 'button' to your import list:
import {
AppRegistry,
StyleSheet,
Text,
View,
Alert
Button,
} from 'react-native';

Adding a View By Clicking a Button- REACT NATIVE

How can I add a view to the bottom of the screen with the click of a button, which is at the top of the screen, in React Native?
you make the view at the bottom of the screen conditionally render based on a state and you set it that state to be true on the OnPress method of the button
I think it is better to learn more about state and props and other fundamental concepts in react/react-native first:
https://facebook.github.io/react-vr/docs/components-props-and-state.html
but here is how you can do this:
You need to define a state if you can view that section as
false
, then when the button pressed, change the value of that state to
true
import React from 'react';
import {Text,View,TouchableOpacity} from 'react-native';
export default class testComponent extends React.Component {
constructor(){
super()
this.state = {
viewSection :false
}
}
renderBottomComponent(){
if(this.state.viewSection) {
return (
<View>
<Text>Hi!</Text>
</View>
)
}
}
buttonPress=()=>{
this.setState({viewSection:true})
}
render() {
return (
<View >
<TouchableOpacity onPress={this.buttonPress}>
<Text> Click Me!</Text>
</TouchableOpacity>
{this.renderBottomComponent()}
</View>
);
}
}
You can try this,
According to my knowledge this is what you want
import React, { useState } from 'react';
import { Button, View } from 'react-native';
export default function Testing() {
const Square = () => (
<View style={{
width: 50,
height: 50,
margin: 10,
backgroundColor: "green",
}} />
);
const [squares, setSquares] = useState([<Square />, <Square />, <Square />]);
return (
<View >
{squares.map(v => v)}
<Button title='add' onPress={() => setSquares([...squares, <Square />])} />
</View >
)
}