how insert line break in alert message in react-native-awesome-alerts - react-native

I'm using react-native-awesome-alerts in my code .
In alert message i want to break the text into a new line
it should be like the below image
alert
please help me how to do it
Here is my code
import React, { Component } from 'react';
import { StyleSheet, View, Text, TouchableOpacity } from 'react-native';
import AwesomeAlert from 'react-native-awesome-alerts';
export default class Alert extends Component {
constructor(props) {
super(props);
this.state = { showAlert: false };
}
showAlert = () => {
this.setState({
showAlert: true
});
};
hideAlert = () => {
this.setState({
showAlert: false
});
};
render() {
const { showAlert } = this.state;
return (
<View style={styles.container}>
<Text>I'm AwesomeAlert</Text>
<TouchableOpacity onPress={() => {
this.showAlert();
}}>
<View style={styles.button}>
<Text style={styles.text}>Try me!</Text>
</View>
</TouchableOpacity>
<AwesomeAlert
show={showAlert}
showProgress={false}
message='Incorrect Username/Password Used{“\n”}Please try again…'
messageStyle={styles.textStyle}
closeOnTouchOutside={true}
closeOnHardwareBackPress={false}
contentContainerStyle={styles.alertStyle}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#fff',
},
button: {
margin: 10,
paddingHorizontal: 10,
paddingVertical: 7,
borderRadius: 5,
backgroundColor: '#AEDEF4',
},
text: {
color: '#fff',
fontSize: 15
},
alertStyle: {
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'white',
height: 100,
width: '60%',
borderWidth: 1,
borderColor: '#fff',
borderRadius: 7,
color: 'red'
},
textStyle: {
fontSize: 14,
color: 'black',
alignItems: 'center'
}
});
i have tried 'Incorrect Username/Password Used{“\n”}Please try again…' but still no luck
please let me know where it is going wrong

You need to change your message string to using backtick ` and add \n. This should work now.
message={`Incorrect Username/Password Used \n Please try again…`}
You might also change the container width to 80% and add textAlign:"centre" to textStyle CSS so that that it look better.
Here is what I managed to produce:

You can add a view with width to 80% and add textAlign: "centre" to AwesomeAlert messageStyle so that it looks better.
<View style={{ width: '80%' }}>
<AwesomeAlert
show={showAlert}
showProgress={false}
message='Incorrect Username/Password Used{“\n”}Please try again…'
messageStyle={styles.textStyle}
closeOnTouchOutside={true}
closeOnHardwareBackPress={false}
contentContainerStyle={styles.alertStyle}
/>
<View>

Add multiple AlertTitle tags inside the alert
<Alert>
<AlertTitle>First line's Text Goes Here</AlertTitle>
<AlertTitle>Second line's Text Goes Here</AlertTitle>
</Alert>

There are two main solutions for this.
Method 1: Just add the '\n' like below
<Text>
First Line {'\n'} Second Line.
</Text>
Method 2: Add the line break it in the string literals, like below.
<Text>
`First Line
Second Line`.
</Text>
For more information, please refer the below tutorial.
https://cutt.ly/ZZ50BCR

Related

I am trying to implement text change and edit ends in TextInput using react-native but it's not quite working. Can any one help me?

I am trying to implement text change and edit ends in TextInput using react-native but it's not quite working.
See the Screenshot Here
Currently, when changing the price by touch input, the price is not affected when click off.
Here are my files
CartItem.js:
import React from "react";
import {
View,
TextInput,
Image,
TouchableOpacity,
StyleSheet,
Platform,
Alert,
} from "react-native";
//Colors
import Colors from "../../../utils/Colors";
//NumberFormat
import NumberFormat from "../../../components/UI/NumberFormat";
//Icon
import { MaterialCommunityIcons } from "#expo/vector-icons";
import CustomText from "../../../components/UI/CustomText";
//PropTypes check
import PropTypes from "prop-types";
export class CartItem extends React.PureComponent {
render() {
const { item, onAdd, onDes, onRemove } = this.props;
const AddItemHandler = async () => {
await onAdd();
};
const sum = +item.item.price * +item.quantity;
const checkDesQuantity = async () => {
if (item.quantity == 1) {
Alert.alert(
"Clear cart",
"Are you sure you want to remove the product from the cart?",
[
{
text: "Cancel",
},
{
text: "Yes",
onPress: onRemove,
},
]
);
} else {
await onDes();
}
};
return (
<View style={styles.container}>
<View style={styles.left}>
<Image
style={{
width: "100%",
height: 90,
resizeMode: "stretch",
borderRadius: 5,
}}
source={{ uri: item.item.thumb }}
/>
</View>
<View style={styles.right}>
<View
style={{ flexDirection: "row", justifyContent: "space-between" }}
>
<CustomText style={styles.title}>{item.item.filename}</CustomText>
<View>
<TouchableOpacity onPress={onRemove}>
<MaterialCommunityIcons name='close' size={20} color='#000' />
</TouchableOpacity>
</View>
</View>
<CustomText style={{ color: Colors.grey, fontSize: 12 }}>
Provided by Brinique Livestock LTD
</CustomText>
<NumberFormat price={sum.toString()} />
<View style={styles.box}>
<TouchableOpacity onPress={checkDesQuantity} style={styles.boxMin}>
<MaterialCommunityIcons name='minus' size={16} />
</TouchableOpacity>
Code that I would like to be fixed starts here.
<View>
<TextInput
keyboardType='numeric'
onEndEditing={AddItemHandler}
style={styles.boxText}>{item.quantity}</TextInput>
</View>
Code that I would like to be fixed ends here.
<TouchableOpacity
onPress={AddItemHandler}
style={styles.boxMin}>
<MaterialCommunityIcons name='plus' size={16} />
</TouchableOpacity>
</View>
</View>
</View>
);
}
}
CartItem.propTypes = {
item: PropTypes.object.isRequired,
onAdd: PropTypes.func.isRequired,
onRemove: PropTypes.func.isRequired,
onDes: PropTypes.func.isRequired,
};
const styles = StyleSheet.create({
container: {
flex: 1,
marginHorizontal: 10,
height: 110,
borderBottomWidth: 1,
borderBottomColor: Colors.light_grey,
flexDirection: "row",
paddingVertical: 10,
alignItems: "center",
backgroundColor: "#fff",
paddingHorizontal: 10,
borderRadius: 5,
marginTop: 5,
},
left: {
width: "35%",
height: "100%",
alignItems: "center",
},
right: {
width: "65%",
paddingLeft: 15,
height: 90,
// overflow: "hidden",
},
title: {
fontSize: 14,
},
box: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
height: Platform.OS === "ios" ? 30 : 25,
backgroundColor: Colors.grey,
width: 130,
borderRadius: 5,
paddingHorizontal: 15,
marginTop: 5,
},
boxMin: {
width: "30%",
alignItems: "center",
},
boxText: {
fontSize: 16,
backgroundColor: Colors.white,
padding: 5,
},
});
Use onBlur instead of onEndEditing.
How should the input end triggered?
After a time?
When user hits enter?
When user taps anywhere to close software keyboard?
Instead of
onEndEditing={AddItemHandler}
Use:
onBlur={(e) => {AddItemHandler(e.nativeEvent.text)}}
And ensure that AddItemHandler can handle the value in e.nativeEvent.text.

Long texts getting cropped in Text components React-Native

I have a functional component Comment, which dynamically receives data to show in a socialmedia like application. If a long text is given as a comment, the height of the card is increased accordinly but the last line is cropped by a half. I tried with many solutions I found in other posts, like textBreakStrategy={'simple'} or flexWrap: 'wrap' in the container, but nothing is solving this issue.
As additional information, a lot of Comments are being rendered in a container ScrollView, and the ScrollView is inside a View with flex: 1. I dont think there's any problem with the container.
To give a better idea, here's a picture of a Comment with a long text getting cropped in the last line:
Here is the component's code:
import React, { useState } from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
import AntDesign from 'react-native-vector-icons/AntDesign';
import { formatDistanceToNow } from 'date-fns'
import { es } from 'date-fns/esm/locale'
const Comment = props => {
const amITheCreator = (comment, user) => {
if (comment && user) {
return comment.creator_id === user.id;
}
return false;
};
const user = props.user;
const comment = props.item;
const date = new Date(comment.createdAt);
const relativeDate = formatDistanceToNow(date, { addSuffix: true, locale: es });
const itsMine = amITheCreator(comment, user);
const [liked, setLiked] = useState(comment.liked);
const [likes, setLikes] = useState(comment.likes);
const toggleLike = () => {
if (liked) {
setLikes(likes - 1);
} else {
setLikes(likes + 1);
}
setLiked(!liked);
};
const onLike = () => {
toggleLike();
props.onLike(comment.id);
};
return (
<View style={{ ...styles.container, backgroundColor: itsMine ? '#0095ff' : 'white' }}>
<View style={styles.header}>
<Text style={{ ...styles.owner, color: itsMine ? 'white' : '#222b45' }}>{comment.name}</Text>
<Text style={{ ...styles.date, color: itsMine ? 'white' : '#8f9bb3' }}>{relativeDate}</Text>
</View>
<View style={styles.contentContainer}>
<Text style={{ ...styles.content, color: itsMine ? 'white' : '#222b45' }}>{comment.content}</Text>
</View>
<View style={styles.header}>
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
<AntDesign name={'heart'} color={itsMine ? 'white' : '#8f9bb3'} size={14} />
<Text style={{ ...styles.likes, color: itsMine ? 'white' : '#8f9bb3' }}> {likes ? likes : '0'} Me gusta</Text>
</View>
<TouchableOpacity onPress={onLike}>
{liked ?
<AntDesign name={'heart'} color={'#ff2d55'} size={20} />
:
<AntDesign name={'hearto'} color={itsMine ? 'white' : '#8f9bb3'} size={20} />
}
</TouchableOpacity>
</View>
</View >
);
};
const styles = StyleSheet.create({
container: {
marginHorizontal: 15,
marginBottom: 15,
borderRadius: 7,
padding: 10,
},
header: {
flexDirection: 'row',
justifyContent: 'space-between',
},
owner: {
fontWeight: 'bold',
},
date: {
fontSize: 12,
color: 'white',
},
contentContainer: {
padding: 5,
flexWrap: 'wrap',
},
content: {
fontSize: 16,
alignSelf: 'stretch',
width: '100%',
padding: 5,
},
likes: {
color: 'white',
fontSize: 15,
fontWeight: 'bold',
},
});
export default Comment;

Change color after click on TouchableHighlight in react native

I have done a many research on the color change after press/click. Finally
I got this script for change the state and put it in the TouchableHighlight. But When i clicked on that, only the "underlayColor={'gray'}" is working. Can i get some idea ?
here is my code
import React, { Component } from 'react';
import {
StyleSheet,
Text,
StatusBar ,
TouchableOpacity,
View,
FlatList,
ActivityIndicator,
TouchableHighlight,
PropTypes,
Image,
Alert
} from 'react-native';
import Logo from '../components/Logo';
import Form from '../components/Front';
import {Actions} from 'react-native-router-flux';
export default class Login extends Component<{}> {
constructor() {
super();
this.state = {
dataSource: {},
pressed: false
};
}
izijackpotconfirm() {
Actions.izijackpotconfirm()
}
componentDidMount() {
var that = this;
let items = Array.apply(null, Array(25)).map((v, i) => {
return { id: i+1 };
});
that.setState({
dataSource: items,
});
}
static navigationOptions = {
title: "Izi Jackpot",
headerStyle: {
backgroundColor: "#354247"
},
headerTintColor: "#fff",
headerTitleStyle: {
fontWeight: "bold"
}
};
render() {
var jackpotNumbers = [];
let btn_class = this.state.black ? "NormalSet" : "SelectedSet";
return(
<View style={styles.container}>
<View style={styles.middlecontainer}>
<Text style={styles.logoText}>Please Select 5 Numbers and Submit</Text>
</View>
<FlatList
data={this.state.dataSource}
renderItem={({ item }) => (
<View style={{ flex: 1, flexDirection: 'column', margin: 1 }}>
<TouchableHighlight
onPress={() => { Alert.alert(this.state.pressed) }}
style={[
styles.iziPizi,
this.state.pressed ? { backgroundColor: "blue" } : {}
]}
onHideUnderlay={() => {
this.setState({ pressed: false });
}}
onShowUnderlay={() => {
this.setState({ pressed: true });
}}
underlayColor={'gray'}
>
<Text style={styles.buttonText}>{ item.id}</Text></TouchableHighlight>
</View>
)}
//Setting the number of column
numColumns={5}
keyExtractor={(item, index) => index}
/>
<View style={styles.middlecontainer}>
<TouchableOpacity style={styles.button} onPress={this.izijackpotconfirm} >
<Text style={styles.buttonText}>Submit</Text>
</TouchableOpacity>
</View>
</View>
)
}
}
const styles = StyleSheet.create({
container : {
backgroundColor:'#6F9000',
justifyContent: 'center',
flex: 1,
paddingTop: 30,
},
middlecontainer: {
textAlign: 'center',
alignItems: 'center',
justifyContent :'center',
flex:1
},
signupTextCont : {
flexGrow: 1,
alignItems:'flex-end',
justifyContent :'center',
paddingVertical:16,
flexDirection:'row'
},
signupText: {
color:'rgba(255,255,255,0.6)',
fontSize:16
},
signupButton: {
color:'#ffffff',
fontSize:16,
fontWeight:'500'
},
iziPizi: {
width: 55,
padding: 15,
margin: 5,
borderRadius: 80,
borderWidth: 2,
borderColor: '#FFFFFF',
flex:1
},
iziPiziPress: {
width: 55,
padding: 15,
margin: 5,
backgroundColor:'#1c313a',
borderRadius: 80,
borderWidth: 2,
borderColor: '#FFFFFF',
flex:1
},
button: {
width:300,
backgroundColor:'#1c313a',
borderRadius: 25,
marginVertical: 10,
paddingVertical: 13
},
buttonText: {
fontSize:16,
fontWeight:'500',
color:'#ffffff',
textAlign:'center'
},
logoText : {
color:'#FFFFFF',
fontSize: 16,
fontWeight: '500',
alignItems: 'center',
justifyContent:'center',
},
imageThumbnail: {
justifyContent: 'center',
alignItems: 'center',
height: 100,
},
});
One more thing to say that, i have used FlatList here. Please help on this. Thanks in advance.
The problem is in how you work with the styles inside the Touchable. My advice is to create 2 styles that contain the changes:
style={
this.state.pressed ? styles.pressed : styles.iziPizi
}
Inside the touchable of course:
<TouchableHighlight
onPress={() => { Alert.alert(this.state.pressed) }}
style={
this.state.pressed ? styles.pressed : styles.iziPizi
}
onHideUnderlay={() => {
this.setState({ pressed: false });
}}
onShowUnderlay={() => {
this.setState({ pressed: true });
}}
underlayColor={'gray'}
>
yes. there was a problem in FlatList. but i dont know what is its problem.
use ListItem of native-base instead.
remember that if you want to use ListItem, in constructor change
this.state = {
dataSource: {},
...
}
to
this.state = {
dataSource: [],
}
use array insead. here is a sample code for you.
<View style={{ flex: 1, flexDirection: 'column', margin: 1 }}>
<List>
{this.state.dataSource.map( item =>
<ListItem>
<TouchableHighlight
onPress={() => {}}
onShowUnderlay={this.onPress.bind(this)}
>
<Text style={styles.buttonText}>{ item.id}</Text>
</TouchableHighlight>
</ListItem> )
}
</List>
</View>
Also define onPress method.
another problem in your code is this that you setState of pressed.
it results that all of your element style will be changed. so all of your button backgroundColor will be changed.
so you must define pressed flag for every element in your array and change this flag

Not printed state in React Native

I'm now using React Native. Now I'm trying to print out one of states that are initialized ( for instance, showText herein ). When I recall this value in render, it doesn't show up ( blank ). The way that I recall is "{this.state.showText}". It doesn't produce any error messages.
Maybe because of the same reason, the initial value of TouchableHighlight seems to be blank. I'm completely lost here since a sample app in Facebook Github works fine within the website. Please give me any idea on this matter.
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Image,
ScrollView,
ListView,
TouchableHighlight,
TextInput
} from 'react-native';
class Greeting extends Component {
render() {
return (
<Text>Hello {this.props.name}! {this.props.date}~ Class can be added..{'\n'}</Text>
);
}
}
class Test1 extends Component {
constructor(props) {
super(props);
this.state = {
showText: 'true',
showTextBool: true,
wow: 'ddsdfasdf'
};
}
onSignupPress(){
return "hello";
}
render() {
let display = this.state.showTextBool ? 'true' : 'false';
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native! {this.state.showText} {this.state.showTextBool}
{this.state.wow}
</Text>
<TextInput style={styles.searchInput} value={this.state.wow} placeholder='Search via name or postcode'/>
<TouchableHighlight style={styles.button} underlayColor='#99d9f4'>
<Text style={styles.buttonText}>Go</Text>
</TouchableHighlight>
<Text style={styles.welcome}>
{display} + {this.onSignupPress()} + {this.state.showText}
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
buttonText: {
color: 'white',
alignSelf: 'center'
},
button: {
height: 36,
flex: 1,
flexDirection: 'row',
backgroundColor: '#48BBEC',
borderColor: '#48BBEC',
borderWidth: 1,
borderRadius: 8,
marginBottom: 10,
alignSelf: 'stretch',
justifyContent: 'center'
},
searchInput: {
height: 36,
padding: 4, marginRight: 5,
flex: 4,
fontSize: 18, borderWidth: 1, borderColor: '#48BBEC', borderRadius: 8, color: '#48BBEC'
}
});
AppRegistry.registerComponent('Test1', () => Test1);
I tried your code in react native express page. It renders one "true", but you are expected two (the text and the boolean). In the following part:
Welcome to React Native! {this.state.showText} {this.state.showTextBool}
The text is being rendered properly (it says indeed 'true'), but the boolean is not there, mainly because you cannot render a boolean like that. Try with the following:
{String(this.state.showTextBool)}
This will render the boolean value properly.

Re-render only on button press in react-native

I have a react native screen where 2 text inputs are added by default, while 2 text inputs are added on button press only.
I am able to add text to the first 2 text inputs, but the other 2 are not accepting text, they accept text only when "Add another car" button is pressed again.
What am I missing? Why is the view not re-rendered when I add text.
CarReg.js
'use strict';
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
TextInput
} from 'react-native';
var Button = require('./Button');
var Parse = require('parse/react-native');
class CarReg extends Component {
constructor(props) {
super(props);
this.state = {
carNumber1: "",
carState1: "",
carNumber2: "",
carState2: "",
errorMessage: "",
carEntry: <View/>,
};
}
render() {
const { page } = this.state;
return (
<View style={styles.container}>
<Text
style={[styles.titleContainer, {marginBottom: 30}]}>
Please register your cars, you can add up-to 2 cars </Text>
<Text style={styles.titleContainer}> License plate number: </Text>
<TextInput
style={styles.textInputContainer}
onChangeText={(text) => this.setState({carNumber1: text})}
value={this.state.carNumber1}/>
<Text style={styles.titleContainer}> State: </Text>
<TextInput
style={styles.textInputContainer}
onChangeText={(text) => this.setState({carState1: text})}
value={this.state.carState1}/>
{this.state.carEntry}
<Text>{this.state.errorMessage}</Text>
<Button text="Add another car" onPress={this.onAddCarPress.bind(this)}/>
<Button text="Submit" onPress={this.onSubmitPress.bind(this)}/>
<Button text="I don't have a car" onPress={this.onNoCarPress.bind(this)}/>
</View>
);
}
onAddCarPress() {
this.setState({carEntry:
<View style={styles.addCarView}>
<Text style={styles.titleContainer}> License plate number: </Text>
<TextInput
style={styles.textInputContainer}
onChangeText={(text) => this.setState({carNumber2: text})}
value={this.state.carNumber2}/>
<Text style={styles.titleContainer}> State: </Text>
<TextInput
style={styles.textInputContainer}
onChangeText={(text) => this.setState({carState2: text})}
value={this.state.carState2}/>
</View>
})
}
onSubmitPress() {
this.props.navigator.push({name: 'main'});
}
onNoCarPress() {
this.props.navigator.push({name: 'main'});
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
addCarView: {
backgroundColor: '#F5FCFF',
justifyContent: 'center',
alignItems: 'center',
},
titleContainer: {
fontSize: 20,
fontFamily: 'Helvetica',
},
textInputContainer: {
padding: 4,
margin: 5,
borderWidth: 1,
borderRadius: 10,
width: 200,
height: 40,
fontFamily: 'Helvetica',
alignSelf: 'center',
marginBottom: 10,
marginTop: 10,
},
});
module.exports = CarReg;
Button.js
'use strict';
import React, { Component } from 'react';
import {
StyleSheet,
Text,
TouchableHighlight,
} from 'react-native';
class Button extends Component {
constructor(props) {
super(props);
}
render() {
return (
<TouchableHighlight
style={styles.container}
onPress={this.props.onPress}
underlayColor ='gray'>
<Text style={styles.textContainer}>{this.props.text}</Text>
</TouchableHighlight>
);
}
}
const styles = StyleSheet.create({
container: {
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
marginTop: 10,
padding: 5,
borderWidth: 1,
borderRadius: 10,
},
textContainer: {
fontFamily: 'Helvetica',
justifyContent: 'center',
alignSelf: 'center',
textAlign: 'center',
flex:1,
fontSize: 20,
}
});
module.exports = Button;
I created the demo of your code on the rnplay. (only ios version.)
I think it's not the good idea to push html to your state. The state is for the data like an array, a boolean and templates (strings). This is only my opinion, of course.
After you click to submit button, look at the console.