Declaring array for use in React Native AutoComplete search engine - javascript

Not sure where I go about declaring the array with which I want to search from, any assistance would be appreciated. I believe my issue is that I am declaring the "services' array in the incorrect area but I am not sure where else to put it! Or if the commas are the right character to be using in between strings/services
import React, { useState, Component } from 'react';
import { StyleSheet, StatusBar, View, Text, Button, TouchableOpacity } from 'react-native';
import AutoComplete from 'react-native-autocomplete-input';
class CareProviderSequenceScreen extends Component {
constructor (props) {
super (props);
this.state = {
services: [],
query: '',
}
}
render() {
const query = this.state;
const services = {
"Pick up my Prescription",
'Pick up groceries',
'Pick up dry cleaning',
'Pick up my pet',
}
return (
<View style={styles.container}>
<Autocomplete
autoCapitalize="none"
autoCorrect={false}
containerStyle={styles.autocompleteContainer}
//data to show in suggestion
data={services.length === 1 && comp(query, services[0].title) ? [] : services}
//default value if you want to set something in input
defaultValue={query}
/*onchange of the text changing the state of the query which will trigger
the findFilm method to show the suggestions*/
onChangeText={text => this.setState({ query: text })}
placeholder="Enter your need"
renderItem={({ item }) => (
//you can change the view you want to show in suggestion from here
<TouchableOpacity onPress={() => this.setState({ query: item.title })}>
<Text style={styles.itemText}>
{item.title} ({item.release_date})
</Text>
</TouchableOpacity>
)}
/>
<View style={styles.descriptionContainer}>
{services.length > 0 ? (
<Text style={styles.infoText}>{this.state.query}</Text>
) : (
<Text style={styles.infoText}>Enter The Film Title</Text>
)}
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: '#F5FCFF',
flex: 1,
padding: 16,
marginTop: 40,
},
autocompleteContainer: {
backgroundColor: '#ffffff',
borderWidth: 0,
},
descriptionContainer: {
flex: 1,
justifyContent: 'center',
},
itemText: {
fontSize: 15,
paddingTop: 5,
paddingBottom: 5,
margin: 2,
},
infoText: {
textAlign: 'center',
fontSize: 16,
},
});
export default CareProviderSequenceScreen ;
CareProviderSequenceScreen .navigationOptions = () => ({
title: "Home & Personal Care",
headerTintColor: '#9EBBD7',
headerStyle: {
height: 65,
backgroundColor: '#1E5797',
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 1,
},
shadowOpacity: 0.20,
shadowRadius: 1.41,
elevation: 2,}
});

First, you are assigning an object to services array.
Second, you are not accessing the query state properly. It should be
const { query } = this.state

Related

React Native Elevation shadow does not work properly

I am new to React Native, I tried to create a component for my radio button but I encountered some issue with the Style when I added the elevation, and it is adding the shadow inside the View instead of outside of the View
Here is my code
import {Text, View, StyleSheet} from 'react-native';
import {RadioButton} from 'react-native-paper';
import {
ScrollView,
TextInput,
TouchableOpacity,
} from "react-native-gesture-handler";
function Chosen({values, onChange, defaultIndex, selectedIndexAtt, renderComponent}){
const [index, setIndex] = useState(defaultIndex ? defaultIndex : 0);
const getRadioStatus = (itemIndex) => {
return index == itemIndex ? 'checked' : 'unchecked';
}
const handleRadioPress = (itemIndex) => {
setIndex(itemIndex);
onChange(itemIndex);
}
return(
<ScrollView style={styles.container}>
<View style={styles.containerRow}>
{values.map((item, index)=> {
return (<View style={styles.itemContainer}>
<View style={styles.item}>
{renderComponent(item)}
<View style={styles.radioButton}>
<RadioButton value={item[selectedIndexAtt ? selectedIndexAtt : index]}
status={getRadioStatus(item[selectedIndexAtt ? selectedIndexAtt : index])}
onPress={() => {
handleRadioPress(item[selectedIndexAtt ? selectedIndexAtt : index])
}}/>
</View>
</View>
</View>)
})}
</View>
</ScrollView>
);
}
const styles = StyleSheet.create({
container:{
flexDirection: 'column',
flex: 1
},
containerRow:{
flexDirection: 'row',
flexWrap: 'wrap',
},
itemContainer: {
width: "50%",
padding: 1
},
item: {
flexDirection: 'row',
margin: 10,
borderWidth: 1,
borderColor: 'rgba(105,105,105,0.6)',
borderRadius: 15,
elevation: 0.1
},
radioButton: {
justifyContent: 'center',
flex: 1,
alignItems: 'flex-end'
}
});
export default Chosen;
and here is how I call it from the parent
<Chosen values={dummyData} defaultIndex={dummyData[0].id} selectedIndexAtt='id' renderComponent={(item) => {
return (
<View>
<Text>{item.name}</Text>
</View>
)
}} onChange={onChange}></Chosen>
and the result is this:
elevation shadow issue
Can someone please help me with this?
You have to provide this for a shadow in react native. Change the values according to your need.
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 10,
},
shadowOpacity: 0.5,
shadowRadius: 10,
elevation: 20,

react-native-draggable-flatlist not working inside ScrollView

I am struggling for last couple of months to achieve a requirement where I'm having a draggable flatlist and a flatlist in a single scrollview and I should able to scroll the whole content.
The draggable flatlist should have autoscroll as well, that means when the list is too long and I'm trying to drag it out of the viewport, the list should scroll automatically unless I drop it.
I know the requirement is pretty much tricky but I am not getting any clue to make it work completely.
I am using the below code and I am using 'react-native-draggable-flatlist'(https://github.com/computerjazz/react-native-draggable-flatlist) for this purpose.
Code:
import React from 'react';
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
TouchableOpacity
} from 'react-native';
import {
Header,
LearnMoreLinks,
Colors,
DebugInstructions,
ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
import DraggableFlatList from 'react-native-draggable-flatlist'
import { Component } from 'react'
const exampleData = [...Array(20)].map((d, index) => ({
key: `item-${index}`, // For example only -- don't use index as your key!
label: index,
backgroundColor: `rgb(${Math.floor(Math.random() * 255)}, ${index *
5}, ${132})`
}));
class App extends Component {
state = {
data: exampleData,
scrollEnabled: true
};
onEnableScroll = (value: boolean) => {
this.setState({
enableScrollViewScroll: value,
});
};
renderItem = ({ item, index, drag, isActive }) => {
return (
<TouchableOpacity
style={{
height: 100,
backgroundColor: isActive ? "blue" : item.backgroundColor,
alignItems: "center",
justifyContent: "center"
}}
onLongPress={drag}
>
<Text
style={{
fontWeight: "bold",
color: "white",
fontSize: 32
}}
>
{item.label}
</Text>
</TouchableOpacity>
);
};
render() {
return (
<ScrollView
style={{ backgroundColor: '#000', flex: 1 }}
contentContainerStyle={{ paddingTop: 800, paddingBottom: 100 }}
scrollEnabled={this.state.scrollEnabled}
>
<DraggableFlatList
data={this.state.data}
renderItem={this.renderItem}
keyExtractor={(item, index) => `draggable-item-${item.key}`}
onMoveBegin={() => this.setState({ scrollEnabled: false })}
onMoveEnd={({ data }) => {
this.setState({ scrollEnabled: true, data });
}}
/>
<FlatList
data={this.state.data}
renderItem={this.renderItem}
keyExtractor={(item, index) => `draggable-item-${item.key}`}
/>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
scrollView: {
backgroundColor: Colors.lighter,
},
engine: {
position: 'absolute',
right: 0,
},
body: {
backgroundColor: Colors.white,
},
sectionContainer: {
marginTop: 32,
paddingHorizontal: 24,
},
sectionTitle: {
fontSize: 24,
fontWeight: '600',
color: Colors.black,
},
sectionDescription: {
marginTop: 8,
fontSize: 18,
fontWeight: '400',
color: Colors.dark,
},
highlight: {
fontWeight: '700',
},
footer: {
color: Colors.dark,
fontSize: 12,
fontWeight: '600',
padding: 4,
paddingRight: 12,
textAlign: 'right',
},
});
export default App;
You should use ListFooterComponent and ListHeaderComponent method to render items.
Please change your render method like below code.
render() {
return (
<View
style={{ backgroundColor: '#000', flex: 1 }}
>
<DraggableFlatList
data={this.state.data}
renderItem={this.renderItem}
keyExtractor={(item, index) => `draggable-item-${item.key}`}
onMoveBegin={() => this.setState({ scrollEnabled: false })}
onMoveEnd={({ data }) => {
this.setState({ scrollEnabled: true, data });
}}
ListFooterComponent={() => {
return <View>
<FlatList
data={this.state.data}
renderItem={this.renderItem}
keyExtractor={(item, index) => `draggable-item-${item.key}`}
/>
</View>
}}
/>
</View>
);
}
In my case, I have another ScrollView composition.
My solution was found in this repository:
React Native Draggable FlatList
I replaced:
ScrollView -> NestableScrollContainer
DraggableFlatList -> NestableDraggableFlatList
Initially there was one DraggableFlatList but in this case I was able to scroll via the DraggableFlatList

Unable to update state in react native component using onChangeText

I have been trying to update the email and password value on submitting the form
so that I can pass them in my login API parameters. But I have tried almost everything, the value of this.state won't just update. Every time I try to print the value in console log e.g: cosole.log(this.state.email), it prints empty string i.e the default value set previously.
Here is my code below:
login.js
import React, { Component } from 'react';
import { ThemeProvider, Button } from 'react-native-elements';
import BliszFloatingLabel from './BliszFloatingLabel'
import {
StyleSheet,
Text,
View,
Image,
TextInput,
Animated,
ImageBackground,
Linking
} from 'react-native';
const domain = 'http://1xx.xxx.xx.xxx:8000';
class Login extends Component {
state = {
email: '',
password: '',
}
LoginAPI = (e,p) => {
console.log(e, "####")
}
handleEmail = (text) => {
this.setState({ email: text })
}
handlePassword = (text) => {
this.setState({ password: text })
}
goToSignUpScreen=() =>{
this.props.navigation.navigate('SignUpScreen');
};
goToForgotPasswordScreen=() =>{
this.props.navigation.navigate('ForgotPasswordScreen');
};
render() {
return (
<View style={styles.container} >
<ImageBackground source={require('../bgrndlogin.jpeg')} style={styles.image} >
<View style={styles.heading}>
<Image style={styles.logo} source={require('../loginlogo.png')} />
<Text style={styles.logoText}>Login</Text>
<Text style={styles.logodesc}>Please Login to continue --></Text>
</View>
<View style={styles.form_container}>
<BliszFloatingLabel
label="Email Id"
value={this.state.email}
onChangeText = {this.handleEmail}
onBlur={this.handleBluremail}
/>
<BliszFloatingLabel
label="Password"
value={this.state.password}
onChangeText = {this.handlePassword}
onBlur={this.handleBlurpwd}
secureTextEntry={true}
/>
<ThemeProvider theme={theme}>
<Button buttonStyle={{
opacity: 0.6,
backgroundColor: '#CC2C24',
borderColor: 'white',
borderWidth: 1,
width: 200,
height: 50,
marginTop: 30,
marginLeft: '20%',
alignItems: 'center',
justifyContent: "center"
}}
title="Login"
type="outline"
onPress = {
() => this.LoginAPI(this.state.email, this.state.password)
}
/>
</ThemeProvider>
<Text style={{
marginTop: 70,
color: '#CC2C24',
fontSize: 16,
fontWeight: "bold"
}}
onPress={
this.goToForgotPasswordScreen
}>
Forgot Password?
</Text>
<Text style={{
marginTop: 20,
color: '#CC2C24',
fontSize: 16,
fontWeight: "bold"
}}
onPress={
this.goToSignUpScreen
}>
Don't have an Account?
</Text>
</View>
</ImageBackground>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
logo: {
width: 115,
height: 50,
},
logoText: {
color: 'white',
fontSize: 36,
fontWeight: "bold"
},
logodesc: {
color: '#CC2C24',
fontSize: 18,
fontWeight: "bold"
},
heading: {
flex: 3,
marginLeft:20,
marginTop:30
},
form_container: {
flex: 7,
marginLeft:20,
marginTop:30,
marginRight: 20,
},
image: {
flex: 1,
resizeMode: "cover",
justifyContent: "center"
},
});
const theme = {
Button: {
titleStyle: {
color: 'white',
fontWeight: "bold",
fontSize: 18
},
},
};
export default Login;
I have created a common form as below which I inherit everywhere :
BliszFloatingLabel.js
import React, { Component } from 'react';
import {
Text,
View,
TextInput,
Animated,
} from 'react-native';
class BliszFloatingLabel extends Component {
state = {
entry: '',
isFocused: false,
};
UNSAFE_componentWillMount() {
this._animatedIsFocused = new Animated.Value(0);
}
handleInputChange = (inputName, inputValue) => {
this.setState(state => ({
...state,
[inputName]: inputValue // <-- Put square brackets
}))
}
handleFocus = () => this.setState({ isFocused: true })
handleBlur = () => this.setState({ isFocused: true?this.state.entry!='' :true})
handleValueChange = (entry) => this.setState({ entry });
componentDidUpdate() {
Animated.timing(this._animatedIsFocused, {
toValue: this.state.isFocused ? 1 : 0,
duration: 200,
useNativeDriver: true,
}).start();
}
render() {
// console.log(this.state.entry)
const { label, ...props } = this.props;
const { isFocused } = this.state;
const labelStyle = {
position: 'absolute',
left: 0,
top: !isFocused ? 40 : 0,
fontSize: !isFocused ? 16 : 12,
color: 'white',
};
return (
<View style={{ paddingTop: 20,paddingBottom:20 }}>
<Text style={labelStyle}>
{label}
</Text>
<TextInput
{...props}
style={{
height: 50, fontSize: 16, color: 'white', borderBottomWidth: 1, borderBottomColor: "white"
}}
value={this.state.entry}
onChangeText={this.handleValueChange}
onFocus={this.handleFocus}
onBlur={this.handleBlur}
blurOnSubmit
/>
</View>
)
}
}
export default BliszFloatingLabel;
Instead of passing onChangeText like this onChangeText={this.handleValueChange} pass in a callback in BliszFloatingLabel and also in Login component.
onChangeText={(text)=>this.handleValueChange(text)}
Snack with the fixture.
https://snack.expo.io/#waheed25/d16fb3

Realm React Native get crash

I am using Realm for the first time, I have written the simple code in app.js
import React, { Component } from 'react';
import { StyleSheet, Platform, View, Image, Text, TextInput, TouchableOpacity, Alert } from 'react-native';
var Realm = require('realm');
let realm ;
export default class App extends Component{
constructor(){
super();
this.state = {
Student_Name : '',
Student_Class : '',
Student_Subject : ''
}
realm = new Realm({
schema: [{name: 'Student_Info',
properties:
{
student_id: {type: 'int', default: 0},
student_name: 'string',
student_class: 'string',
student_subject: 'string'
}}]
});
}
add_Student=()=>{
realm.write(() => {
var ID = realm.objects('Student_Info').length + 1;
realm.create('Student_Info', {
student_id: ID,
student_name: this.state.Student_Name,
student_class: this.state.Student_Class,
student_subject : this.state.Student_Subject
});
});
Alert.alert("Student Details Added Successfully.")
}
render() {
var A = realm.objects('Student_Info');
var myJSON = JSON.stringify(A);
return (
<View style={styles.MainContainer}>
<TextInput
placeholder="Enter Student Name"
style = { styles.TextInputStyle }
underlineColorAndroid = "transparent"
onChangeText = { ( text ) => { this.setState({ Student_Name: text })} }
/>
<TextInput
placeholder="Enter Student Class"
style = { styles.TextInputStyle }
underlineColorAndroid = "transparent"
onChangeText = { ( text ) => { this.setState({ Student_Class: text })} }
/>
<TextInput
placeholder="Enter Student Subject"
style = { styles.TextInputStyle }
underlineColorAndroid = "transparent"
onChangeText = { ( text ) => { this.setState({ Student_Subject: text })} }
/>
<TouchableOpacity onPress={this.add_Student} activeOpacity={0.7} style={styles.button} >
<Text style={styles.TextStyle}> CLICK HERE TO ADD STUDENT DETAILS </Text>
</TouchableOpacity>
<Text style={{marginTop: 10}}>{myJSON}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
MainContainer :{
flex:1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: (Platform.OS) === 'ios' ? 20 : 0,
margin: 10
},
TextInputStyle:
{
borderWidth: 1,
borderColor: '#009688',
width: '100%',
height: 40,
borderRadius: 10,
marginBottom: 10,
textAlign: 'center',
},
button: {
width: '100%',
height: 40,
padding: 10,
backgroundColor: '#4CAF50',
borderRadius:7,
marginTop: 12
},
TextStyle:{
color:'#fff',
textAlign:'center',
}
});
Now I am getting the error like this in picture http://prntscr.com/mym0zo, as I have already said, I am using the realm for the very first time, so can't understand the problem.
Please help me get this resolved.
My dependancies are
"dependencies": {
"react": "16.8.3",
"react-native": "0.59.1",
"realm": "^2.25.0"
},

List item for chat from Array inside array React Native

This is my code for Chat Box, the window where I have "In" and "Out" messages are appearing.
import React, { Component } from "react";
import {
StyleSheet,
Text,
View,
TouchableOpacity,
TextInput,
FlatList,
Platform,
AsyncStorage
} from "react-native";
import Tutor from "../image/krutika.jpg";
import {
Container,
Header,
Left,
Input,
Body,
Right,
Thumbnail,
Button
} from "native-base";
import FontAwesome from "react-native-vector-icons/FontAwesome";
import Ionicons from "react-native-vector-icons/Ionicons";
import Icon1 from "react-native-vector-icons/FontAwesome";
import axios from "axios";
export default class ChatBox extends Component {
static navigationOptions = {
header: null
};
state = {
group_msgs: [],
student_id: null
};
renderDate = date => {
return <Text style={styles.time}>{date}</Text>;
};
componentWillMount = () => {
this.loading();
const { navigation } = this.props;
groupName = navigation.getParam("groupName");
group_id = navigation.getParam("group_id");
};
loading = async () => {
const userid = await AsyncStorage.getItem("user_id");
this.state.student_id = userid;
try {
let { data } = await axios.get('https://www.qualpros.com/chat/imApi/getMessage?groupId=6&limit=10&start=0&userId=62').then(response => {
// console.log(response)
if (response.status == 200) {
this.setState({ group_msgs: response.data.response.message });
console.log(response.data.response)
} else {
}
});
} catch (err) {
console.log(err);
}
};
render() {
return (
<Container>
<Header style={{ backgroundColor: "#d91009" }}>
<Left style={{ flex: 1, flexDirection: "row" }}>
<TouchableOpacity
style={styles.backArrow}
onPress={() => this.props.navigation.navigate("ChatScreen")}
>
<FontAwesome name="angle-left" size={30} color="#fff" />
</TouchableOpacity>
<Thumbnail
source={Tutor}
style={{
marginLeft: 8,
width: 30,
height: 30,
borderRadius: 30 / 2
}}
/>
</Left>
<Body>
<Text
onPress={() => {
this.props.navigation.navigate("Groupmembers", {
group_id:group_id,
groupname:groupName,
});
}}
style={{
alignSelf: Platform.OS == "android" ? "center" : null,
fontSize: 17,
color: "#fff"
}}
>
{groupName}
</Text>
</Body>
<Right>
<Button
style={{ backgroundColor: "#d91009" }}
onPress={() => {
this.props.navigation.navigate("TutorCalender");
}}
>
<Icon1 active name="calendar" size={24} color="#FFF" />
</Button>
</Right>
</Header>
<View style={styles.container}>
<FlatList
style={styles.list}
data={this.state.group_msgs}
keyExtractor={item => {
return item.m_id;
}}
renderItem={message => {
console.log(item);
const item = message.item;
let inMessage = (item.sender === this.state.userid) ? 'in' : 'out';
let itemStyle = inMessage ? styles.itemIn : styles.itemOut;
return (
<View style={[styles.item, itemStyle]}>
<View style={[styles.balloon]}>
<Text>{item.message}</Text>
</View>
</View>
);
}}
/>
<View style={styles.footer}>
<View style={styles.inputContainer}>
<TextInput
style={styles.inputs}
placeholder="Write a message..."
underlineColorAndroid="transparent"
onChangeText={name_address => this.setState({ name_address })}
/>
</View>
{/* <TouchableOpacity style={styles.btnSend}>
<Ionicons name="md-send" size={36} color='#d91009' /> style={styles.iconSend} />
</TouchableOpacity> */}
</View>
</View>
</Container>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
list: {
paddingHorizontal: 17
},
footer: {
flexDirection: "row",
height: 60,
backgroundColor: "#eeeeee",
paddingHorizontal: 10,
padding: 5
},
btnSend: {
//color: "#d91009",
width: 40,
height: 40,
borderRadius: 360,
alignItems: "center",
justifyContent: "center"
},
iconSend: {
width: 30,
height: 30,
alignSelf: "center"
},
inputContainer: {
borderBottomColor: "#F5FCFF",
backgroundColor: "#FFFFFF",
borderRadius: 30,
borderBottomWidth: 1,
height: 40,
flexDirection: "row",
alignItems: "center",
flex: 1,
marginRight: 10
},
inputs: {
height: 40,
marginLeft: 16,
borderBottomColor: "#FFFFFF",
flex: 1
},
balloon: {
maxWidth: 250,
padding: 15,
borderRadius: 20
},
itemIn: {
alignSelf: "flex-start",
backgroundColor: "#eeeeee"
},
itemOut: {
alignSelf: "flex-end",
backgroundColor: "#DCF8C5"
},
time: {
alignSelf: "flex-end",
margin: 15,
fontSize: 12,
color: "#808080"
},
item: {
marginVertical: 14,
flex: 1,
flexDirection: "row",
borderRadius: 300,
padding: 1
}
});
I am using axios to fetch the api, the api response is coming as an Array inside the array but nothing is coming on the screen.
I can get it with storing response upto message but then I can't have the loop on messages.
Please help.
Thanks in advance
When doing a GET request to the endpoint in your code the response looks as follows:
{
"status":{
"code":200,
"message":"Success"
},
"totalMessage":6,
"recentMessageId":228,
"response":[
...
]
}
Inside the response object there's an array of message objects so you can't use response.data.response.message when setting state. That part of your code needs to be:
this.setState({ group_msgs: response.data.response });
Now you should be able to iterate through the group_msgs object to get the message key value for each item in the array.
Also in the FlatList component you should have
keyExtractor={item => {
return item.message.m_id;
}}
Your renderItem seems to be wrong as well, see should be something like this:
renderItem={ ({item}) => {
let inMessage = (item.sender.usedId === this.state.userid) ? 'in' : 'out';
let itemStyle = inMessage ? styles.itemIn : styles.itemOut;
return (
<View style={[styles.item, itemStyle]}>
<View style={[styles.balloon]}>
<Text>{item.message.message}</Text>
</View>
</View>
);
}}
I strongly suggest you take a look at the structure of the response object since that's where you are failing at the moment.

Categories

Resources