Prompt event occurs from eveywhere in the screen when taped - react-native

I am new in React Native. My problem occurred when prompt the event by clicking the Image icon. I want the prompt event occur from the image button only. But when i click or tap anywhere in the screen, it opens.What can be done to solve this issue ? In stylesheet, marginBottom and marginRight also doesn't work, so I use marginTop and marginLeft. What can be done to solve this also ?
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Image,
TouchableHighlight
} from 'react-native';
import ToolbarAndroid from 'ToolbarAndroid';
import Prompt from 'react-native-prompt';
class DevForm extends Component {
constructor(props) {
super(props);
this.state = {
message: '',
promptVisible: false
};
}
render() {
return (
<View style = {styles.container}>
<ToolbarAndroid style = {styles.toolbar}>
<Text style = {styles.titleText}> Data Collector </Text>
</ToolbarAndroid>
<TouchableHighlight
onPress={() => this.setState({ promptVisible: true })}
>
<Image
source = {require('./icon_container/ic_plus_circle_add_new_form.png')}
style = {styles.addButton}
/>
</TouchableHighlight>
<View style = {{ flex: 1, justifyContent: 'center' }}>
<Text style = {{ fontSize: 20 }}>
{this.state.message}
</Text>
</View>
<Prompt
title = "Write title of form "
placeholder = "Your title is here"
visible = {this.state.promptVisible}
onCancel = {() => this.setState({ promptVisible: false, message: 'You cancel it !!!'})}
onSubmit={(value) => this.setState({ promptVisible: false, message: `You title is "${value}"` })}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
},
toolbar: {
height: 56,
backgroundColor: '#3F51B5'
},
titleText: {
fontSize: 16,
fontWeight: 'bold',
color: '#fff'
},
addButton: {
marginLeft: 270,
marginTop: 420,
height: 50,
width: 50
}
});
AppRegistry.registerComponent('DevForm', () => DevForm);

So What I could figure out after running the code is that prompt dialog only appears in the area covered by marginLeft and marginTop not the complete screen if you didn't have marginLeft and marginTop it would have been difficult to reproduce this bug. There might be a bug in the npm library "react-native-prompt" that you are using in this example other than that I am not sure what's actually going wrong.

Related

In React Native, is there anything similar to the activeOpacity prop in the new Pressable component?

In TouchableOpacity, it is possible to set the value of the activeOpacity prop to dim the button after it was pressed, so the user had feedback that their touch was registered and does not pressing the same button repeatedly.
Is there anything similar in the new Pressable component? Or any way to easily achieve the same effect?
You can try following example to achieve same functionality:
import React, { useState } from 'react';
import { Pressable, StyleSheet, Text, View } from 'react-native';
const App = () => {
const [timesPressed, setTimesPressed] = useState(0);
let textLog = '';
if (timesPressed > 1) {
textLog = timesPressed + 'x onPress';
} else if (timesPressed > 0) {
textLog = 'onPress';
}
return (
<View style={styles.container}>
<Pressable
onPress={() => {
setTimesPressed((current) => current + 1);
}}
style={({ pressed }) => [
{
backgroundColor: 'gray',
opacity: pressed ? 0.2 : 1
},
styles.wrapperCustom
]}>
{({ pressed }) => (
<Text style={styles.text}>
{pressed ? 'Pressed!' : 'Press Me'}
</Text>
)}
</Pressable>
<View style={styles.logBox}>
<Text testID="pressable_press_console">{textLog}</Text>
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
},
text: {
fontSize: 16
},
wrapperCustom: {
borderRadius: 8,
padding: 6
},
logBox: {
padding: 20,
margin: 10,
borderWidth: StyleSheet.hairlineWidth,
borderColor: '#f0f0f0',
backgroundColor: '#f9f9f9'
}
});
export default App;

Hide the bottom image view when showing keyboard react-native

How I can hide this picture...
Thank you for any help!
You can use Keyboard in ReactNative to listen for changes of keyboard and hide your image when the keyboard is visible.
check below sample code
import * as React from "react";
import { View, Keyboard, TextInput, Image } from "react-native";
export default class App extends React.Component {
state = {
isKeyboadVisible: false,
text: ""
};
componentDidMount() {
this.keyboardDidShowListener = Keyboard.addListener(
"keyboardDidShow",
this._keyboardDidShow
);
this.keyboardDidHideListener = Keyboard.addListener(
"keyboardDidHide",
this._keyboardDidHide
);
}
componentWillUnmount() {
this.keyboardDidShowListener.remove();
this.keyboardDidHideListener.remove();
}
_keyboardDidShow = () => {
this.setState({
isKeyboadVisible: true
});
};
_keyboardDidHide = () => {
this.setState({
isKeyboadVisible: false
});
};
render() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<TextInput
style={{
height: 40,
width: "80%",
borderColor: "red",
borderWidth: 1,
marginBottom: 10
}}
onChangeText={text => this.setState({ text })}
value={this.state.text}
/>
{!this.state.isKeyboadVisible && (
<Image
style={{ width: 100, height: 100 }}
source={{ uri: "https://reactnative.dev/img/tiny_logo.png" }}
/>
)}
</View>
);
}
}
Change the above code according to your requirements.
Hope this helps you. Feel free for doubts.
You need to using ScrollView to wrapper your view. Therefore, when you click to input component, keyboard will overlap your picture.
https://reactnative.dev/docs/using-a-scrollview#__docusaurus
Another solution is try to using KeyboardAvoidingView
https://reactnative.dev/docs/keyboardavoidingview

How to add a text input to alert in react native

Can someone help with adding a text input to an alert in react native. Is it possible? I searched and found results that deals with multiple line text input which is not the case with me. Thanks in advance
This is possible. I believe this was only available initially for AlertIOS however it seems to have been intergrated to React Native Alert.
Edit: Although its added to Alert it does not seem to work for Android
Use
import { Alert } from 'react-native';
onButtonPress = () => {
Alert.prompt(
"Enter password",
"Enter your password to claim your $1.5B in lottery winnings",
[
{
text: "Cancel",
onPress: () => console.log("Cancel Pressed"),
style: "cancel"
},
{
text: "OK",
onPress: password => console.log("OK Pressed, password: " + password)
}
],
"secure-text"
);
};
}
More details: https://reactnative.dev/docs/alertios
Use react-native-dialog it works across platform and is simple enough.
There is no way you could add a text input to the Alert component according to the documentation, You will need to create a custom component by yourself in order to achieve that, example: use customise modal or use react-native-simple-dialogs
No way
Just use custom modal or third party library to achieve this...
Here is a spoiler using a custom Modal:
import React, { FC } from 'react'
import { View, TextInput, Modal, GestureResponderEvent } from 'react-native';
import { BoldText, IOSButton } from '..';
import { colors } from '../../constants';
import { customModalStyles, defaultStyles } from '../../styles';
interface Props {
modalVisible: boolean;
// onRequestClose,
textOne: string;
buttonOneTitle: string;
onPressOne: (event: GestureResponderEvent) => void;
value: string,
onChangeText: (text: string) => void;,
placeholder: string
}
const InputModal: FC<Props> = ({
modalVisible,
// onRequestClose,
textOne,
buttonOneTitle,
onPressOne,
value,
onChangeText,
placeholder
}) => {
return (
<Modal
animationType="fade"
transparent={true}
visible={modalVisible}
// onRequestClose={onRequestClose}
>
<View style={customModalStyles.centeredView}>
<View style={customModalStyles.modalView}>
<BoldText
style={customModalStyles.textSize}>{textOne}
</BoldText>
<TextInput
secureTextEntry
autoCapitalize="none"
style={[
defaultStyles.inputStyle,
defaultStyles.textInputShadow,
]}
value={value}
onChangeText={onChangeText}
placeholder={placeholder}
placeholderTextColor={colors.placeHolder}
/>
<IOSButton title={buttonOneTitle}
onPress={onPressOne}
/>
</View>
</View>
</Modal>
)
}
export default InputModal;
And the styles:
import { StyleSheet } from 'react-native';
import { colors } from '../constants';
import styleConstants from './styleConstants';
const customModalStyles = StyleSheet.create({
buttonsContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
},
centeredView: {
flex: 1,
justifyContent: 'flex-end',
alignItems: 'center',
marginBottom: 20,
},
modalView: {
justifyContent: 'space-around',
alignItems: 'center',
width: styleConstants.width < 1000 ? 320 : 400,
height: styleConstants.height < 1000 ? 320 : 400,
backgroundColor: colors.primary,
borderRadius: 20,
paddingHorizontal: 15,
paddingTop: 10,
shadowColor: colors.secondary,
shadowOffset: {
width: 0,
height: 4,
},
shadowOpacity: 0.55,
shadowRadius: 8,
elevation: 20,
},
textSize: {
textAlign: 'center',
fontSize: styleConstants.fontSizeSM,
},
});
export default customModalStyles;
Then one may use it like this:
{modalVisible && (
<InputModal
modalVisible={modalVisible}
textOne={`...`}
buttonOneTitle="..."
onPressOne={async () => {
setModalVisible(false);
validatePasswordEtc()
}}
placeholder="..."
value={password}
onChangeText={handleChangePassword}
/>
)}
If you think for a moment you will find that an alert and a modal are both a kind of pop-up components. And that leads you to create your own pop-up component instead of using ready-made if you don't have it.
return (
<Modal
animationType="slide"
transparent={true}
onBackdropPress={() => console.log('Pressed')}
visible={props.modalVisible}
onRequestClose={ResetValues}>
<View
style={{
position: 'absolute',
bottom: 0,
right: 0,
backgroundColor: '#4D4D4D',
width: (windowWidth * 100) / 100,
height: (windowHeight * 100) / 100,
}}>
!!!!!!!!! your elements here like text,input,buttons and etc....!!!!!
</View>
</Modal>
);

React Native render and switch with navigator onPress

I've just started to develop with React Native a week ago.
Can anyone help me with simple render and switch onPress to another view?
I've read tones of examples, but most of them are cutted or not well documents as if on FaceBook Doc pages. There was no totally completed example with Nav.
Here is what was done yet - View that should be rendered 1st:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Image,
TextInput,
TouchableHighlight,
TouchableNativeFeedback,
Platform,
Navigator
} from 'react-native';
export default class SignUp extends Component {
buttonClicked() {
console.log('Hi');
this.props.navigator.push({title: 'SignUp', component:SignUp});
}
render() {
var TouchableElement = TouchableHighlight;
if (Platform.OS === ANDROID_PLATFORM) {
TouchableElement = TouchableNativeFeedback;
}
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to Cross-Profi!
</Text>
<Text style={styles.field_row}>
<TextInput style={styles.stdfield} placeholder="Profession" />
</Text>
<Text style={styles.field_row}>
<TextInput style={styles.stdfield} placeholder="E-mail" />
</Text>
<Text style={styles.field_row}>
<TextInput style={styles.stdfield} secureTextEntry={true} placeholder="Password" />
</Text>
<TouchableElement style={styles.button} onPress={this.buttonClicked.bind(this)}>
<View>
<Text style={styles.buttonText}>Register</Text>
</View>
</TouchableElement>
{/* <Image source={require("./img/super_car.png")} style={{width:120,height:100}} />*/}
<Text style={styles.instructions}>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'lightblue',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
color: 'darkred',
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
field_row: {
textAlign: 'center',
color: '#999999',
margin: 3,
},
stdfield: {
backgroundColor: 'darkgray',
height: 50,
width: 220,
textAlign: 'center'
},
button: {
borderColor:'blue',
borderWidth: 2,
margin: 5
},
buttonText: {
fontSize: 18,
fontWeight: 'bold'
}
});
const ANDROID_PLATFORM = 'android';
Navigator class that should render different views:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Platform,
Navigator
} from 'react-native';
var MainActivity = require('./app/MainActivity.js');
var SignUp = require('./app/SignUp.js');
class AwesomeProject extends Component {
/*constructor(props) {
super(props);
this.state = {text: ''};
}*/
render() {
// this.props.navigator.push({title:'SignUp'});
return (
<Navigator initialRoute={{title:'SignUp', component:SignUp}}
configureScene={() => {
return Navigator.SceneConfigs.FloatFromRight;
}}
renderScene={(route, navigator) =>
{
console.log(route, navigator);
if (route.component) {
return React.createElement(route.component, {navigator});
}
}
} />
);
}
}
const ANDROID_PLATFORM = 'android';
const routes = [
{title: 'MainActivity', component: MainActivity},
{title: 'SignUp', component: SignUp},
];
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
It doesn't seem to be clear whether there must be require of a class and declaration of class as export default.
There is an error: Element type is invalid: expected a string, ... but got object etc
Help with examples would be great. Thx
In your require call, you should either replace it import statement or use default property of require module i.e:
var MainActivity = require('./app/MainActivity.js').default;
or use
import MainActivity from "./app/MainActivity";
In ES6, require doesn't assign default property of module to variable.
See this blog post for better understanding of require working in es6

How can I change the text in TabBarIOS in React Native?

In the react native documentation I cannot find a way to change the bottom words?
<TabBarItemIOS
name="greenTab"
icon={_ix_DEPRECATED('more')}
accessibilityLabel="Green Tab"
selected={this.state.selectedTab === 'greenTab'}
onPress={() => {
this.setState({
selectedTab: 'greenTab',
presses: this.state.presses + 1
});
}}>
{this._renderContent('#21551C', 'Green Tab')}
</TabBarItemIOS>
What is the accessibilityLabel ?
The TabBarItem allows you to use one of the iOS preset icons from UITabBarSystemItem, and in your sample code it's using the "More" icon. Crucially though, the documentation for UITabBarSystemItem states:
The title and image of system tab bar items cannot be changed.
If you set the icon to either a data-uri or a local image, rather than an icon from UITabBarSystemItem, you'll be able to override the text on the item to whatever you want using the title prop.
You can try something like that for your TabBarIOS.Item with a custom icon
import React, { Component } from 'react'
import { AppRegistry, StyleSheet, Text, View, TouchableOpacity, TabBarIOS } from 'react-native'
const base64Icon = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEsAAABLCAQAAACSR7JhAAADtUlEQVR4Ac3YA2Bj6QLH0XPT1Fzbtm29tW3btm3bfLZtv7e2ObZnms7d8Uw098tuetPzrxv8wiISrtVudrG2JXQZ4VOv+qUfmqCGGl1mqLhoA52oZlb0mrjsnhKpgeUNEs91Z0pd1kvihA3ULGVHiQO2narKSHKkEMulm9VgUyE60s1aWoMQUbpZOWE+kaqs4eLEjdIlZTcFZB0ndc1+lhB1lZrIuk5P2aib1NBpZaL+JaOGIt0ls47SKzLC7CqrlGF6RZ09HGoNy1lYl2aRSWL5GuzqWU1KafRdoRp0iOQEiDzgZPnG6DbldcomadViflnl/cL93tOoVbsOLVM2jylvdWjXolWX1hmfZbGR/wjypDjFLSZIRov09BgYmtUqPQPlQrPapecLgTIy0jMgPKtTeob2zWtrGH3xvjUkPCtNg/tm1rjwrMa+mdUkPd3hWbH0jArPGiU9ufCsNNWFZ40wpwn+62/66R2RUtoso1OB34tnLOcy7YB1fUdc9e0q3yru8PGM773vXsuZ5YIZX+5xmHwHGVvlrGPN6ZSiP1smOsMMde40wKv2VmwPPVXNut4sVpUreZiLBHi0qln/VQeI/LTMYXpsJtFiclUN+5HVZazim+Ky+7sAvxWnvjXrJFneVtLWLyPJu9K3cXLWeOlbMTlrIelbMDlrLenrjEQOtIF+fuI9xRp9ZBFp6+b6WT8RrxEpdK64BuvHgDk+vUy+b5hYk6zfyfs051gRoNO1usU12WWRWL73/MMEy9pMi9qIrR4ZpV16Rrvduxazmy1FSvuFXRkqTnE7m2kdb5U8xGjLw/spRr1uTov4uOgQE+0N/DvFrG/Jt7i/FzwxbA9kDanhf2w+t4V97G8lrT7wc08aA2QNUkuTfW/KimT01wdlfK4yEw030VfT0RtZbzjeMprNq8m8tnSTASrTLti64oBNdpmMQm0eEwvfPwRbUBywG5TzjPCsdwk3IeAXjQblLCoXnDVeoAz6SfJNk5TTzytCNZk/POtTSV40NwOFWzw86wNJRpubpXsn60NJFlHeqlYRbslqZm2jnEZ3qcSKgm0kTli3zZVS7y/iivZTweYXJ26Y+RTbV1zh3hYkgyFGSTKPfRVbRqWWVReaxYeSLarYv1Qqsmh1s95S7G+eEWK0f3jYKTbV6bOwepjfhtafsvUsqrQvrGC8YhmnO9cSCk3yuY984F1vesdHYhWJ5FvASlacshUsajFt2mUM9pqzvKGcyNJW0arTKN1GGGzQlH0tXwLDgQTurS8eIQAAAABJRU5ErkJggg=='
class ReactNativePlayground extends Component {
constructor(props) {
super(props)
this.state = {
selectedTab: "more",
tabBarItemTitle: "More"
}
}
render() {
return (
<TabBarIOS>
<TabBarIOS.Item selected={this.state.selectedTab === "more"}
title={this.state.tabBarItemTitle}
icon={{uri: base64Icon, scale: 3}}>
<View style={styles.container}>
<TouchableOpacity onPress={ (event) => { this._changeTabItemTitle() } }>
<Text style={styles.button}>Tap to Change Item Title</Text>
</TouchableOpacity>
</View>
</TabBarIOS.Item>
</TabBarIOS>
);
}
_changeTabItemTitle() {
this.setState({ tabBarItemTitle: "New More" })
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
},
button: {
fontSize: 20,
color: "white",
textAlign: 'center',
backgroundColor: "#1155DD",
borderRadius: 5,
height: 30,
margin: 30,
},
});
AppRegistry.registerComponent('ReactNativePlayground', () => ReactNativePlayground);