Style "currentLocationLabel" from react-native-google-places-autocomplete - react-native

I'm using react-native-google-places-autocomplete, and i would like to style currentlocation label to make it a marker icon + text,and i also want to make it visible once in the screen not till clicking on the textinput.
my code looks like this:
export default class VilleC extends React.Component {
render() {
loc = () => {
return(
<View style={{flexDirection:'row',marginLeft:10}}>
<EntypoI color={'grey'} size={20} name={'direction'} />
<Text style={{color:'black',marginLeft:10}}>Autour de moi</Text>
</View>);
}
return (
<View style={{flex:1}}>
<GooglePlacesAutocomplete
placeholder='Où ? (adresse,ville...)'
query={{
key: GOOGLE_PLACES_API_KEY,
language: 'fr', // language of the results
components: 'country:ma',
}}
fetchDetails = {true}
currentLocation={true}
>>>>>>>>>>< currentLocationLabel={// what's in function loc i would like to make it here }
GooglePlacesDetailsQuery = {{
fields: ['geometry']
}}
onPress={(data, details = null) => {console.log(details.geometry.location.lat);
console.log(data.description);
NavigationService.navigate('Résultat',{screen:'Résultats',params:{lien: this.props.route.params.lien, choice: this.props.route.params.choix,lat:details.geometry.location.lat,lng:details.geometry.location.lng,loc:data.description}})
}}
onFail={(error) => console.error(error)}
requestUrl={{
url:
'https://cors-anywhere.herokuapp.com/https://maps.googleapis.com/maps/api',
useOnPlatform: 'web',
}} // this in only required for use on the web. See https://git.io/JflFv more for details. // variable styles can t find error
enablePoweredByContainer={false}
styles={{
textInputContainer: {
backgroundColor: 'rgba(0,0,0,0)',
borderTopWidth: 0,
borderBottomWidth: 0,
},
textInput: {
borderRadius:0,
marginLeft: 3,
marginRight: 3,
height: 38,
color: '#5d5d5d',
fontSize: 16,
paddingLeft:20,
shadowColor: "grey",
shadowOpacity: 0.8,
shadowRadius: 2,
shadowOffset: {
height: 1,
width: 0,
},
elevation: 3,
},
predefinedPlacesDescription: {
color: '#1faadb',
},
}}
/>
</View>
);
}
}
i would really appreciate your help!

You can use the renderRow prop to add an icon to the current location, and you can use the autFocus prop to open the input automatically.
Something like this:
export default class App extends React.Component {
render() {
return (
<View style={{ flex: 1 }}>
<GooglePlacesAutocomplete
placeholder="Où ? (adresse,ville...)"
query={{
key: 'GOOGLE_PLACES_API_KEY',
language: 'fr', // language of the results
components: 'country:ma',
}}
autoFocus={true}
fetchDetails={true}
currentLocation={true}
currentLocationLabel="Autour de moi"
renderRow={(row) =>
row.isCurrentLocation ? (
<View style={{ flexDirection: 'row', marginLeft: 10 }}>
<Text>icon</Text>
<Text style={{ color: 'black', marginLeft: 10 }}>
{row.description}
</Text>
</View>
) : (
<Text>{row.description}</Text>
)
}
GooglePlacesDetailsQuery={{
fields: ['geometry'],
}}
onPress={(data, details = null) => {
console.log(details.geometry.location.lat);
console.log(data.description);
}}
onFail={(error) => console.error(error)}
requestUrl={{
url:
'https://cors-anywhere.herokuapp.com/https://maps.googleapis.com/maps/api',
useOnPlatform: 'web',
}} // this in only required for use on the web. See https://git.io/JflFv more for details. // variable styles can t find error
enablePoweredByContainer={false}
styles={{
textInputContainer: {
backgroundColor: 'rgba(0,0,0,0)',
borderTopWidth: 0,
borderBottomWidth: 0,
},
textInput: {
borderRadius: 0,
marginLeft: 3,
marginRight: 3,
height: 38,
color: '#5d5d5d',
fontSize: 16,
paddingLeft: 20,
shadowColor: 'grey',
shadowOpacity: 0.8,
shadowRadius: 2,
shadowOffset: {
height: 1,
width: 0,
},
elevation: 3,
},
predefinedPlacesDescription: {
color: '#1faadb',
},
}}
/>
</View>
);
}
}

Related

How to implement swipeable in react native gesture handler

I want to implement a swipe to delete feature on flatlist data. I can get the swipe to work, but it only registers after the touch input is lifted. When I start dragging, the card does not initially drag, but it swipes after I lift the input. How can I make it so it starts dragging when I start moving the card?
Current Code:
export default class AppleStyleSwipeableRow extends Component {
private renderRightAction = (x: number, dragX) => {
const trans = dragX.interpolate({
inputRange: [0, 1],
outputRange: [x, 0],
extrapolate: "clamp",
});
const pressHandler = () => {
this.close();
Alert.alert("hi");
};
return (
<Animated.View
style={{
flex: 1,
borderRadius: 15,
height: 120,
transform: [{ translateX: trans }],
}}
>
<RectButton
style={[
styles.rightAction,
{ backgroundColor: "transparent", height: 50 },
]}
onPress={pressHandler}
>
<SquircleView
style={StyleSheet.absoluteFill}
squircleParams={{
cornerSmoothing: 0.6,
cornerRadius: 15,
fillColor: "#FF3B30",
}}
>
<Image
style={{
width: 17.37 * 1.5,
height: 19.66 * 1.5,
justifyContent: "center",
alignSelf: "center",
top: 40,
right: 3.5,
}}
source={require("../../assets/trash.fill.png")}
></Image>
</SquircleView>
</RectButton>
</Animated.View>
);
};
private renderRightActions = (
progress: Animated.AnimatedInterpolation,
_dragAnimatedValue: Animated.AnimatedInterpolation
) => (
<View
style={{
width: 90,
flexDirection: I18nManager.isRTL ? "row-reverse" : "row",
}}
>
{this.renderRightAction(90, progress)}
</View>
);
private swipeableRow?: Swipeable;
private updateRef = (ref: Swipeable) => {
this.swipeableRow = ref;
};
private close = () => {
this.swipeableRow?.close();
};
render() {
const { children } = this.props;
return (
<Swipeable
containerStyle={{ borderRadius: 15 }}
childrenContainerStyle={{ backgroundColor: "white", borderRadius: 15 }}
ref={this.updateRef}
friction={3}
enableTrackpadTwoFingerGesture
rightThreshold={40}
renderRightActions={this.renderRightActions}
>
{children}
</Swipeable>
);
}
}
const styles = StyleSheet.create({
actionText: {
color: "white",
fontSize: 16,
backgroundColor: "transparent",
padding: 10,
},
rightAction: {
alignItems: "center",
flex: 1,
justifyContent: "center",
left: 10,
},
});
ScreenA.tsx
const RenderItem = ({ item }) => {
return (
<View style={{ height: 120, width: W_WIDTH * 0.9, zIndex: -100 }}>
<Image
source={require("../../assets/pin.png")}
style={{
position: "absolute",
width: 40,
height: 40,
}}
/>
<Text
style={{
fontSize: 22,
paddingRight: 16,
color: "black",
fontFamily: "Medium",
left: 45,
top: 6,
}}
>
Foo
</Text>
</View>
);
};
const ScreenA = () => {
const SwipeableRow = ({ item }) => {
return (
<RectButton
style={{
width: W_WIDTH * 0.9,
height: 120,
alignItems: "center",
backgroundColor: "#f3f2f8",
borderRadius: 10,
marginHorizontal: 20,
marginTop: 20,
}}
onPress={() =>
navigation.navigate("ScreenB")
}
>
<AppleStyleSwipeableRow>
<RenderItem item={item} />
</AppleStyleSwipeableRow>
</RectButton>
);
};
return (
<StatusBar style={colorScheme == "dark" ? "light" : "dark"} />
<ScrollView
style={[
styles.container,
{
backgroundColor: colorScheme == "dark" ? "black" : "white",
},
]}
contentInsetAdjustmentBehavior="automatic"
keyboardDismissMode="on-drag"
>
<FlatList
data={bookmarks}
keyExtractor={(item) => item.country}
renderItem={({ item }) => <SwipeableRow item={item} />}
// renderItem={renderItem}
showsVerticalScrollIndicator={false}
/>
</ScrollView>
);
};
}
Does your RectButton have an onPressIn prop? That's what you'll need to use - if it doesn't have it, switch it out for a Pressable or other component with this prop.

GooglePlacesAutocomplete styling on the list content of places is not working,not able to do wrapping the places react-native

I m using GooglePlacesAutocomplete where while typing getting the list of places but some places text containing more than that,so I wanted to wrap the text there.
<GooglePlacesAutocomplete
placeholder='Where To ?'
minLength={4}
autoFocus={true}
listViewDisplayed="auto"
returnKeyType={'search'}
fetchDetails={true}
onPress={(data, details = null) => {
props.notifyChange(details.geometry.location,data);
}}
query={{
key: 'chghgdhgfhgfjhdhklkl',
language: 'en',
}}
nearbyPlacesAPI= 'GooglePlacesSearch'
debounce={200}
styles={ styles }>
</GooglePlacesAutocomplete>
and my styles for that is as follows
const styles = StyleSheet.create({
textInputContainer:{
backgroundColor: 'rgba(0,0,0,0)',
borderTopWidth: 0,
borderBottomWidth:0,
zIndex:999,
width:'90%',
},
textInput: {
marginLeft: 0,
marginRight: 0,
height: 45,
color: '#5d5d5d',
fontSize: 16,
borderWidth:1,
zIndex:999,
},
predefinedPlacesDescription: {
color: '#1faadb'
},
listView:{
top:45.5,
zIndex:10,
position: 'absolute',
color: 'black',
backgroundColor:"white",
width:'89%',
},
separator:{
flex: 1,
height: StyleSheet.hairlineWidth,
backgroundColor: 'blue',
},
description:{
flexDirection:"row",
flexWrap:"wrap",
fontSize:14,
maxWidth:'89%',
},
});
refer this link https://reactnativeexample.com/customizable-google-places-autocomplete-component-for-ios-and-android-react-native-apps/
but not able to find the solution.help would be appreciated
The width of the ListView showing the results has its width hardcoded to window.with. That is why you wrapping the text isn't working.
There is a potential workaround, and that would be to split the description into multiple lines. You can do this with the renderRow prop. Styling would need to be adjusted for your specific use case.
<GooglePlacesAutocomplete
placeholder='Where To ?'
minLength={4}
autoFocus={true}
listViewDisplayed="auto"
returnKeyType={'search'}
fetchDetails={true}
onPress={(data, details = null) => {
props.notifyChange(details.geometry.location,data);
}}
query={{
key: 'chghgdhgfhgfjhdhklkl',
language: 'en',
}}
nearbyPlacesAPI= 'GooglePlacesSearch'
debounce={200}
renderRow={(rowData) => {
const title = rowData.structured_formatting.main_text;
const address = rowData.structured_formatting.secondary_text;
return (
<View>
<Text style={{ fontSize: 14 }}>{title}</Text>
<Text style={{ fontSize: 14 }}>{address}</Text>
</View>
);
}}
styles={ styles }>
</GooglePlacesAutocomplete>
You would need to add row to your styles and you can description from styles, because it is being overwritten by renderRow
row: {
height: "100%",
},
Disclosure: I am the maintainer of this package.
You can even style the field too.
Follow official doc-
<GooglePlacesAutocomplete
placeholder='Enter Location'
minLength={2}
autoFocus={false}
returnKeyType={'default'}
fetchDetails={true}
styles={{
textInputContainer: {
backgroundColor: 'grey',
},
textInput: {
height: 38,
color: '#5d5d5d',
fontSize: 16,
},
predefinedPlacesDescription: {
color: '#1faadb',
},
}}
/>

Flatlist Multiple item Selection not working on React Native

I am creating a multi-select grid Flatlist and it seems to work fine in IOS phone but it doesn't work at all on Android phone. On IOS it can select an item when clicked, but on Android it just flickers when you select/click an item.
I am really, really can't figure it out. Please help.
Thank you,
[Flatlist-Grid as per code][1]
import {
View, TouchableOpacity, StyleSheet, Text, ScrollView,
Image,
} from 'react-native'
import { MaterialIcons } from '#expo/vector-icons';
export default class StoreSelector extends Component {
constructor() {
super()
this.state = {
dataList: [
{ name: 'exp: date', key: '#ffsdsf', image: <Image style={{ height: 110, width: 110, backgroundColor: 'red' }} /> },
{ name: 'exp: date', key: '#01713f', image: <Image style={{ height: 110, width: 110, backgroundColor: 'red' }} /> },
{ name: 'exp: date', key: '#fsdaff', image: <Image style={{ height: 110, width: 110, backgroundColor: 'red' }} /> },
{ name: 'exp: date', key: '#00b0a6', image: <Image style={{ height: 110, width: 110, backgroundColor: 'red' }} /> },
{ name: 'exp: date', key: '#ffgadsf', image: <Image style={{ height: 110, width: 110, backgroundColor: 'red' }} /> },
{ name: 'exp: date', key: '#fdfdf', image: <Image style={{ height: 110, width: 110, backgroundColor: 'red' }} /> },
{ name: 'exp: date', key: '#fsdff', image: <Image style={{ height: 110, width: 110, backgroundColor: 'red' }} /> },
{ name: 'exp: date', key: '#ec008c', image: <Image style={{ height: 110, width: 110, backgroundColor: 'red' }} /> },
{ name: 'exp: date', key: '#005baa', image: <Image style={{ height: 110, width: 110, backgroundColor: 'red' }} /> },
{ name: 'exp: date', key: '#fceff', image: <Image style={{ height: 110, width: 110, backgroundColor: 'red' }} /> },
{ name: 'exp: date', key: '#ffwf', image: <Image style={{ height: 110, width: 110, backgroundColor: 'red' }} /> },
{ name: 'exp: date', key: '#000', image: <Image style={{ height: 110, width: 110, backgroundColor: 'red' }} /> },
{ name: 'exp: date', key: '#ea3440', image: <Image style={{ height: 110, width: 110, backgroundColor: 'red' }} /> },
]
}
}
componentDidMount() {
let arr = this.state.dataList.map((item, index) => {
this.isSelected = false
return { ...item }
})
this.setState({ dataList: arr })
}
selectionHandler = (ind) => {
const { dataList } = this.state
let arr = dataList.map((item, index) => {
if (ind == index) {
item.isSelected = !item.isSelected
}
return { ...item }
})
this.setState({ dataList: arr })
}
render() {
const { dataList } = this.state
return (
<View style={styles.scrollContainer}>
<ScrollView >
<View style={styles.container}>
{
dataList.map((item, index) => {
return (
<TouchableOpacity
key={item.key}
onPress={() => this.selectionHandler(index)}
style={styles.boxContainer}>
<View style={styles.img}>{item.image}</View>
<View>{item.isSelected ? <MaterialIcons name="check-box" size={24} color="#fbbe2f" /> : <MaterialIcons name="check-box-outline-blank" size={24} color="grey" />}</View>
</TouchableOpacity>
)
})
}
</View>
</ScrollView>
</View>
)
}
}
const styles = StyleSheet.create({
scrollContainer: {
flex: 1,
},
container: {
flex: 1,
flexDirection: 'row',
flexWrap: 'wrap',
alignItems: 'center',
},
boxContainer: {
height: 110,
width: 110,
margin: 7,
},
img: {
elevation: 5,
alignItems: 'center',
justifyContent: 'center',
position: 'absolute',
shadowColor: '#000',
shadowOffset: { width: 1, height: 2 },
shadowOpacity: .3,
shadowRadius: 3,
borderWidth: 0.5,
borderColor: '#eee'
}
})
[1]: https://i.stack.imgur.com/hrRVS.png
You have given elevation to image element which is appearing above your checkbox so on select action it gets selected but not visible as it is under the image.
Now question is how will you see the checkbox?
Option 1: Remove the elevation
img: {
alignItems: 'center',
justifyContent: 'center',
position: 'absolute',
shadowColor: '#000',
shadowOffset: { width: 1, height: 2 },
shadowOpacity: .3,
shadowRadius: 3,
borderWidth: 0.5,
borderColor: '#eee'
}
Option 2: Make the elevation of the icons higher then the image elevation
<View>
{item.isSelected ?
<MaterialIcons name="check-box" size={24} color="#fbbe2f" style={{elevation:10}}/>
:
<MaterialIcons name="check-box-outline-blank" size={24} color="grey" style={{elevation:10}}/>}
</View>

React Native: Display FlatList data in Modal

I have a react native flat list that renders some data from a Wordpress website using wp rest api. The flat list is displaying the post correctly, and when clicked, it opens the modal, but I am having some trouble pushing the state to the modal.
Currently, when the modal opens, it shows the same (last post/item) for every item in the flat list. Any suggestions? Any help appreciated.
import React, { Component } from 'react';
import {
Image, Dimensions, View, ActivityIndicator, TouchableOpacity, TouchableHighlight,
WebView, ScrollView, StyleSheet, ImageBackground, FlatList, Text
} from 'react-native';
import Moment from 'moment';
import HTML from 'react-native-render-html';
import Modal from "react-native-modal";
export default class LatestNews extends Component {
constructor(props) {
super(props);
this.state = {
isModalVisible: false,
isLoading: true,
posts: [],
id: null,
};
}
componentDidMount() {
fetch(`http://mywebsite.com/wp-json/wp/v2/posts/?_embed&categories=113`)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
posts: responseJson,
})
})
.catch((error) => {
console.error(error);
});
}
_toggleModal = () =>
this.setState({
isModalVisible: !this.state.isModalVisible,
});
_renderItem = ({item}) => {
return (
<TouchableOpacity onPress={() => this._onPressItem(item.id)} key={item.id}>
<View>
{item._embedded['wp:featuredmedia'].filter(
element => element.id == item.featured_media
).map((subitem, index) => (
<View style={{
margin: '5%',
borderWidth: 1,
borderColor: '#d8d8d8',
borderRadius: 10,
shadowColor: '#000',
shadowOffset: { width: 0, height: 5 },
shadowOpacity: 0.2,
shadowRadius: 8,
elevation: 1,
}}>
<ImageBackground
style={styles.news}
source={{ uri: subitem.media_details.sizes.medium.source_url }}
key={item.id}>
<View style={styles.itemTitle}>
<Text style={{ fontSize: 16, fontWeight: 'bold' }}>
{item.title.rendered}
</Text>
</View>
</ImageBackground>
</View>
))}
</View>
</TouchableOpacity>
)
};
_onPressItem(id) {
this.setState({
isModalVisible: true,
id: id,
});
};
render() {
if (this.state.isLoading == true) {
return (
<View style={{ flex: 1, flexDirection: 'column', justifyContent: 'center', alignItems: 'center', }}>
<ActivityIndicator size="large" color="#1C97F7" />
</View>
)
}
else {
Moment.locale('en');
return (
<View>
{this.state.posts.map((item, index) => (
<Modal isVisible={this.state.isModalVisible} id={this.state.id}>
{item._embedded['wp:featuredmedia'].filter(
element => element.id == item.featured_media
).map((subitem, index) => (
<ScrollView style={
{ flex: 1, backgroundColor: 'white', padding: 20, paddingBottom: 40,}
}>
<ImageBackground
style={styles.news}
source={{ uri: subitem.media_details.sizes.medium.source_url }}
key={item.id} />
<TouchableOpacity onPress={this._toggleModal}>
<Text>Hide me!</Text>
</TouchableOpacity>
<HTML
tagsStyles={{
body: {fontSize: 16, paddingBottom: 20,},
p: {fontSize: 16, fontWeight: "normal", marginTop: 10, marginBottom: 20},
strong: {fontSize: 20,},
blockquote: {fontSize: 20},
a: {fontSize: 16, color: "#0044e2"},
em: {fontSize: 20,},
img: {height: 250, width: 350},
}}
key={item.id}
styleName="paper md-gutter multiline"
html={item.content.rendered}
imagesMaxWidth={Dimensions.get('window').width * .9}
ignoredStyles={['width', 'height', 'video']}
/>
</ScrollView>
))}
</Modal>
))}
<FlatList
data={this.state.posts}
renderItem={this._renderItem}
keyExtractor={(item, index) => index}
/>
</View>
)
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
paddingTop: 0,
},
h1: {
color: 'black',
fontSize: 24,
paddingTop: 20,
fontWeight: 'bold',
},
h2: {
color: 'black',
fontSize: 24,
paddingTop: 20,
fontWeight: 'bold',
},
h3: {
fontSize: 13,
},
button: {
width: '45%',
margin: 5,
backgroundColor: '#492661',
padding: 8,
height: 36,
borderRadius: 18,
},
buttonGrey: {
width: '45%',
margin: 5,
backgroundColor: '#353535',
padding: 8,
height: 36,
borderRadius: 18,
},
buttonText: {
color: 'black',
alignSelf: 'center',
},
highlight: {
backgroundColor: '#f5f5f5',
borderRadius: 50,
width: 100,
height: 100,
marginRight: 20,
alignItems: 'center',
justifyContent: 'center',
borderColor: 'gold',
borderWidth: 0,
},
news: {
backgroundColor: '#f5f5f5',
borderRadius: 10,
width: '100%',
height: 200,
overflow: 'hidden',
},
hero: {
backgroundColor: '#492661',
width: '110%',
height: 260,
alignSelf: 'center',
marginTop: 0,
overflow: 'hidden'
},
itemTitle: {
backgroundColor: 'rgba(255,255,255,0.9)',
paddingVertical: 10,
position: 'absolute',
bottom: 0,
right: 0,
width: '100%',
paddingHorizontal: 10,
},
});
In FlatList, this is the issue it can't re-render again if dataModel is being there. For this You can use this :
in FlatList there is a propsTypes: ExtraData={} in this you should add a new boolean state, and wherever you again add the data in flatlist . set the state for that boolean key , that would help you :
<FlatList
data={this.state.posts}
renderItem={this._renderItem}
keyExtractor={(item, index) => index}
extraData={this.state.extraData}
/>
where you want add flatList data again add this line:
this.setState({extraData:!this.state.extraData})
by this line render method run again , and you will find a new update records.
Use this, this help me.

How to align one component to left and other to right (end of page) react native?

I'm making an app in React Native and I want align a circle with the end of page.
I want to make this:
But it's currently like this and only stays this way:
The complete view:
[
I already tried alignSelf, justifyContent and others but it doesn't work.
I tested this: How to align 2 react native elements, 1 being in the center and 1 on the beginning
But it won't work.
My code:
const ListProductsHeader = () => (
<View>
<View style={style.containerInfo}>
<View style={style.circle} />
<View>
<Text style={style.unityName}>SUPERMERCADO MACCARTNEY</Text>
<Text style={style.subInfo}>Categoria: Mercado</Text>
<Text style={style.subInfo}>Pedido Nº: 1245</Text>
</View>
</View>
<View style={style.containerProducts}>
<Text style={style.productName}>1x 42 - Coca Cola 2L</Text>
<View style={style.minus}></View>
</View>
</View>
);
CSS:
containerProducts:{
paddingTop: 40,
paddingLeft: 15,
flexDirection: 'row',
},
productName: {
alignSelf: 'flex-start',
},
minus:{
width: 20,
height: 20,
borderRadius: 20/2,
backgroundColor: 'red',
},
containerInfo:{
paddingTop:15,
flexDirection:'row',
paddingLeft: 15,
},
unityName:{
fontWeight: 'bold',
paddingLeft: 15,
},
subInfo:{
color: 'gray',
paddingLeft: 15,
},
circle: {
width: 50,
height: 50,
borderRadius: 50/2,
backgroundColor: 'red',
justifyContent: 'flex-end',
},
Lkke to suggest one thing that can help you with this problem
what you need to do is. Everthing is correct except the main view css
<View style={flexDirection:'row',justifyContent : 'space-between'}>
<View style={style.circle} />
<View>
<Text style={style.unityName}>SUPERMERCADO MACCARTNEY</Text>
<Text style={style.subInfo}>Categoria: Mercado</Text>
<Text style={style.subInfo}>Pedido Nº: 1245</Text>
</View>
</View>
<View style={style.containerProducts}>
<Text style={style.productName}>1x 42 - Coca Cola 2L</Text>
<View style={style.minus}></View>
</View>
try this may be it can help you
containerProducts: {
paddingTop: 40,
paddingLeft: 15,
flexDirection: 'row',
justifyContent: 'space-between',
},
Fully Customisable chat in React Native
import React, {Component} from 'react';
import {
Text,
StyleSheet,
View,
TextInput,
TouchableOpacity,
SafeAreaView,
FlatList,
} from 'react-native';
export default class CustomChatScreen extends Component {
state = {
messages: [
{
msg: 'Heloo',
id: Math.random(),
token: '',
email: '',
type: 'server',
},
{
msg: 'Server Message',
id: Math.random(),
token: '',
email: '',
type: 'server',
},
],
value: '',
};
sendMessageToServer = () => {
if (this.state.value !== '') {
let payload = {
msg: this.state.value,
id: Math.random(),
token: '',
email: '',
type: 'client',
};
let mydata = this.state.messages;
mydata.push(payload);
this.setState({
messages: mydata,
value: '',
});
}
};
renderFlatListItem = rowData => {
return (
<View style={styles.flatListContainerStyle}>
{rowData.item.type === 'client' ? (
<View style={styles.clientMsgStyle}>
<Text>{rowData.item.msg}</Text>
</View>
) : (
<View style={styles.serverMsgStyle}>
<Text>{rowData.item.msg}</Text>
</View>
)}
</View>
);
};
render() {
return (
<SafeAreaView style={styles.container}>
<FlatList
data={this.state.messages}
keyExtractor={(item, index) => index.toString()}
renderItem={this.renderFlatListItem}
/>
<View style={styles.sendMessageConatinerStyle}>
<TextInput
style={styles.sendMsgTextInputStyle}
value={this.state.value}
placeholder = {"please type here!"}
placeholderTextColor = {"#000"}
onChangeText={val => this.setState({value: val})}></TextInput>
<TouchableOpacity
style={styles.sendMsgButtonStyle}
onPress={this.sendMessageToServer}>
<Text>Send Message</Text>
</TouchableOpacity>
</View>
</SafeAreaView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
sendMessageConatinerStyle: {
width: '100%',
height: 60,
position: 'absolute',
bottom: 0,
left: 0,
right: 0,
backgroundColor: 'white',
flexDirection: 'row',
},
sendMsgTextInputStyle: {
backgroundColor: '#e0f2f1',
flex: 0.8,
borderTopLeftRadius: 62.5,
borderBottomLeftRadius: 62.5,
padding: 20,
},
sendMsgButtonStyle: {
flex: 0.2,
backgroundColor: '#80cbc4',
borderBottomRightRadius: 62.5,
borderTopRightRadius: 62.5,
fontSize: 18,
justifyContent: 'center',
alignItems: 'center',
},
flatListContainerStyle: {
backgroundColor: '#e0f7fa',
marginTop: 10,
},
clientMsgStyle: {
backgroundColor: '#ffab91',
borderRadius: 20,
padding: 15,
alignSelf: 'flex-end',
},
serverMsgStyle: {
backgroundColor: '#4fc3f7',
borderRadius: 20,
padding: 15,
alignSelf: 'flex-start',
},
});