// Here I am trying to delete List item from Flat List .
Data is populating from JSON on Flat List now I have to delete particular list item data form list , for that I am using "Swipeout" . but getting error "Type error: undefined is not an object(evaluting this.2.viewNote.bind")
Please help . Where am going wrong and how can I do this
import React, { Component } from 'react';
import { View, Text, TextInput,
FooterTab,Button,TouchableOpacity, ScrollView, StyleSheet,
ActivityIndicator ,Header,FlatList} from 'react-native';
import {Icon} from 'native-base';
import { Table, Row, Rows } from 'react-native-table-component';
import { createStackNavigator } from 'react-navigation';
import { SearchBar } from 'react-native-elements';
import Swipeout from 'react-native-swipeout';
let swipeBtns = [{
text: 'Delete',
backgroundColor: 'red',
underlayColor: 'rgba(0, 0, 0, 1, 0.6)',
onPress: () => { this.deleteNote(item) }
}];
export default class OpenApplianceIssue extends Component {
constructor() {
super();
this.state = {
AbcSdata: null,
loading: true,
search: '',
tableData: [], qrData: '', selectedPriority: '',
selectedIssue: '', selectedReason: '', selectedTriedRestart: '',
selectedPowerLED: '', selectedBurning: '', selectedNoise: '',
};
this.setDate = this.setDate.bind(this);
}
setDate(newDate) {
}
_loadInitialState = async () => {
const { navigation } = this.props;
const qdata = navigation.getParam('data', 'NA').split(',');
var len = qdata.length;
const tData = [];
console.log(len);
for(let i=0; i<len; i++)
{
var data = qdata[i].split(':');
const entry = []
entry.push(`${data[0]}`);
entry.push(`${data[1]}`);
tData.push(entry);
}
this.setState({tableData: tData } );
console.log(this.state.tableData);
this.setState({loading: true});
}
componentDidMount() {
this._loadInitialState().done();
this.createViewGroup();
}
createViewGroup = async () => {
try {
const response = await fetch(
'http:/Dsenze/userapi/sensor/viewsensor',
{
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
"password": 'admin',
"username": 'admin',
"startlimit":"0",
"valuelimit":"10",
}),
}
);
const responseJson = await response.json();
const { sensorData } = responseJson;
this.setState({
AbcSdata: sensorData,
loading: false,
});
} catch (e) {
console.error(e);
}
};
updateSearch = search => {
this.setState({ search });
};
keyExtractor = ({ id }) => id.toString();
keyExtractor = ({ inventory }) => inventory.toString();
renderItem = ({ item }) => (
<Swipeout right={swipeBtns}>
<TouchableOpacity
style={styles.item}
activeOpacity={0.4}
onPress={this.viewNote.bind(this, item)} >
<Text >Id : {item.id}</Text>
<Text>Inventory : {item.inventory}</Text>
<Text>SensorType : {item.sensorType}</Text>
<Text>TypeName : {item.typeName}</Text>
</TouchableOpacity>
</Swipeout>
);
viewNote(item) {
this.props.navigator.push({
title: 'The Note',
component: ViewNote,
passProps: {
noteText: item,
noteId: this.noteId(item),
}
});
}
onClickListener = (viewId) => {
if(viewId == 'tag')
{
this.props.navigation.navigate('AddSensors');
}}
renderSeparator = () => {
return (
<View
style={{
height: 1,
width: "86%",
backgroundColor: "#CED0CE",
}}
/>
);
};
render() {
const { loading, AbcSdata } = this.state;
const state = this.state;
return (
<ScrollView>
<View style={styles.container1}>
<Button full rounded
style={{fontSize: 20, color: 'green'}}
styleDisabled={{color: 'red'}}
onPress={() => this.onClickListener('tag')}
title="Add Sensors"
>
Add Sensors
</Button>
</View>
<View style={styles.container1}>
{this.state.loading ? (
<ActivityIndicator size="large" />
) :
(
<FlatList
data={AbcSdata}
renderItem={this.renderItem}
keyExtractor={this.keyExtractor}
ItemSeparatorComponent={this.renderSeparator}
/>
)}
</View>
<View>
<Text
style={{alignSelf: 'center', fontWeight: 'bold', color: 'black'}} >
Inventory Details
</Text>
<Table borderStyle={{borderWidth: 2, borderColor: '#c8e1ff', padding:10,paddingBottom: 10}}>
<Rows data={state.tableData} textStyle={styles.text}/>
</Table>
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create(
{
container1:
{
flex: 1,
alignItems: 'stretch',
fontFamily: "vincHand",
color: 'blue'
},
header_footer_style:{
width: '100%',
height: 44,
backgroundColor: '#4169E1',
alignItems: 'center',
justifyContent: 'center',
color:'#ffffff',
},
Progressbar:{
justifyContent: 'center',
alignItems: 'center',
color: 'blue',
},
ListContainer :{
borderColor: '#48BBEC',
backgroundColor: '#000000',
color:'red',
alignSelf: 'stretch' ,
},
container2:
{
flex: 1,
justifyContent: 'center',
alignItems: 'stretch',
paddingHorizontal: 15
},
inputBox:{
width:300,
borderColor: '#48BBEC',
backgroundColor: '#F8F8FF',
borderRadius:25,
paddingHorizontal:16,
fontSize:16,
color:'#000000',
marginVertical:10,
},
button:{
width:300,
backgroundColor:'#4169E1',
borderRadius:25,
marginVertical:10,
paddingVertical:16
},
buttonText:{
fontSize:16,
fontWeight:'500',
color:'#ffffff',
textAlign:'center'
},
textStyle:{
fontSize:16,
fontWeight:'500',
color:'#ffffff',
textAlign:'center'
},
item:
{
padding: 15
},
text:
{
fontSize: 18
},
button:{
width:300,
backgroundColor:'#4169E1',
borderRadius:25,
marginVertical:10,
paddingVertical:16
},
buttonText:{
fontSize:16,
fontWeight:'500',
color:'red',
textAlign:'center'
},
separator:
{
height: 2,
backgroundColor: 'rgba(0,0,0,0.5)'
},
container: { flex: 1, padding: 16, paddingTop: 30, backgroundColor: '#fff' },
head: { height: 40, backgroundColor: '#f1f8ff' },
text: { margin: 6 }
});
Thanks .
First thing first,
Try using fat-arrow functions whenever possible, which will automatically solve your binding issues.
You will have to use the extraData= {this.state.activeRow} in your flatlist with newly added state activeRow.
I have updated your renderItem().
Check out the following updated code. Hope this helps.
import * as React from 'react';
import { View, Text, TextInput,
FooterTab, Button, TouchableOpacity, ScrollView, StyleSheet,
ActivityIndicator, Header, FlatList } from 'react-native';
import { Table, Row, Rows } from 'react-native-table-component';
import { createStackNavigator } from 'react-navigation';
import { SearchBar } from 'react-native-elements';
import { Constants } from 'expo';
// You can import from local files
import AssetExample from './components/AssetExample';
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
import Swipeout from 'react-native-swipeout';
export default class App extends React.Component {
constructor() {
super();
this.state = {
AbcSdata: null,
loading: true,
search: '',
tableData: [], qrData: '', selectedPriority: '',
selectedIssue: '', selectedReason: '', selectedTriedRestart: '',
selectedPowerLED: '', selectedBurning: '', selectedNoise: '',
rowID:'',
activeRow: null
};
this.setDate = this.setDate.bind(this);
}
swipeBtns = [{
text: 'Delete',
type: 'delete',
backgroundColor: 'red',
underlayColor: 'rgba(0, 0, 0, 1, 0.6)',
onPress: () => {
console.log("Deleting Row with Id ", this.state.activeRow);
this.deleteNote(this.state.activeRow);
}
}];
removeItem = (items, i) =>
items.slice(0, i).concat(items.slice(i + 1, items.length));
deleteNote = (rowIndex) => {
//add your custome logic to delete the array element with index.
// this will temporary delete from the state.
let filteredData = this.removeItem(this.state.AbcSdata,rowIndex);
this.setState({AbcSdata: [] },()=> {
this.setState({AbcSdata: filteredData },()=> {console.log("Row deleted.", rowIndex)});
});
};
setDate(newDate) {
}
_loadInitialState = async () => {
const { navigation } = this.props;
const qdata = navigation.getParam('data', 'NA').split(',');
var len = qdata.length;
const tData = [];
console.log(len);
for (let i = 0; i < len; i++) {
var data = qdata[i].split(':');
const entry = []
entry.push(`${data[0]}`);
entry.push(`${data[1]}`);
tData.push(entry);
}
this.setState({ tableData: tData });
console.log(this.state.tableData);
this.setState({ loading: true });
}
componentDidMount() {
//this._loadInitialState().done();
this.createViewGroup();
}
createViewGroup = async () => {
try {
const response = await fetch(
'/Dsenze/userapi/sensor/viewsensor',
{
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
"password": 'admin',
"username": 'admin',
"startlimit": "0",
"valuelimit": "10",
}),
}
);
const responseJson = await response.json();
const { sensorData } = responseJson;
this.setState({
AbcSdata: sensorData,
loading: false,
});
} catch (e) {
console.error(e);
}
};
updateSearch = search => {
this.setState({ search });
};
keyExtractor = ({ id }) => id.toString();
keyExtractor = ({ inventory }) => inventory.toString();
onSwipeOpen(rowId, direction) {
if(typeof direction !== 'undefined'){
this.setState({activeRow:rowId});
console.log("Active Row",rowId);
}
}
renderItem = ({ item, index }) => (
<Swipeout
right={this.swipeBtns}
close={(this.state.activeRow !== index)}
rowID={index}
sectionId= {1}
autoClose = {true}
onOpen = {(secId, rowId, direction) => this.onSwipeOpen(rowId, direction)}
>
<TouchableOpacity
style={styles.item}
activeOpacity={0.4}
onPress={this.viewNote(item)} >
<Text >Id : {item.id}</Text>
<Text>Inventory : {item.inventory}</Text>
<Text>SensorType : {item.sensorType}</Text>
<Text>TypeName : {item.typeName}</Text>
</TouchableOpacity>
</Swipeout>
);
viewNote =(item) => {
this.props.navigator.push({
title: 'The Note',
component: this.ViewNote,
passProps: {
noteText: item,
noteId: this.noteId(item),
}
});
console.log("View Note Success");
}
onClickListener = (viewId) => {
if (viewId == 'tag') {
this.props.navigation.navigate('AddSensors');
}
}
renderSeparator = () => {
return (
<View
style={{
height: 1,
width: "86%",
backgroundColor: "#CED0CE",
}}
/>
);
};
render() {
const { loading, AbcSdata } = this.state;
const state = this.state;
return (
<ScrollView>
<View style={styles.container1}>
<Button full rounded
style={{ fontSize: 20, color: 'green' }}
styleDisabled={{ color: 'red' }}
onPress={() => this.onClickListener('tag')}
title="Add Sensors"
>
Add Sensors
</Button>
</View>
<View style={styles.container1}>
{this.state.loading ? (
<ActivityIndicator size="large" />
) :
(
<FlatList
data={AbcSdata}
renderItem={this.renderItem}
keyExtractor={this.keyExtractor}
extraData= {this.state.activeRow}
ItemSeparatorComponent={this.renderSeparator}
/>
)}
</View>
<View>
<Text
style={{ alignSelf: 'center', fontWeight: 'bold', color: 'black' }} >
Inventory Details
</Text>
<Table borderStyle={{ borderWidth: 2, borderColor: '#c8e1ff', padding: 10, paddingBottom: 10 }}>
<Rows data={state.tableData} textStyle={styles.text} />
</Table>
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
},
});
Related
In React-Native, how do I set borderRadius to Text-components?
I've tried using borderRadius in text stylesheet but it not work:
import { formatPhone, mapNameWithLocalContact } from '#chat/common/Utils/ChatUtils';
import ChatFunctions from '#chat/service/ChatFunctions';
import { Colors, Text } from '#momo-platform/component-kits';
import React from 'react';
import { StyleSheet, View, TextStyle } from 'react-native';
import { parseValue } from 'react-native-controlled-mentions';
import { MessageText } from 'react-native-gifted-chat';
// #ts-ignore
import ParsedText from 'react-native-parsed-text';
import { partTypes } from '../menstions';
const textStyle = {
fontSize: 16,
lineHeight: 20,
marginTop: 5,
marginBottom: 5,
marginLeft: 10,
marginRight: 10,
};
const styles = {
left: StyleSheet.create({
container: {},
text: {
color: 'black',
...textStyle,
},
link: {
color: 'black',
textDecorationLine: 'underline',
},
textMention: {
color: Colors.pink_05_b,
fontWeight: 'bold',
},
mentionMe: isMe =>
isMe
? {
color: Colors.white,
backgroundColor: Colors.pink_05_b,
}
: {},
}),
right: StyleSheet.create({
container: {},
text: {
color: 'white',
...textStyle,
},
link: {
color: 'white',
textDecorationLine: 'underline',
},
textMention: {
color: 'white',
fontWeight: 'bold',
},
mentionMe: () => ({}),
}),
};
export default class MessageTextCustom extends MessageText {
constructor() {
super(...arguments);
}
render() {
const linkStyle = [
styles[this.props.position].link,
this.props.linkStyle && this.props.linkStyle[this.props.position],
];
const { parts } = parseValue(this.props.currentMessage.text, partTypes);
return (
<View
style={[
styles[this.props.position].container,
this.props.containerStyle && this.props.containerStyle[this.props.position],
]}
>
<ParsedText
style={[
styles[this.props.position].text,
this.props.textStyle && this.props.textStyle[this.props.position],
this.props.customTextStyle,
]}
parse={[
...this.props.parsePatterns(linkStyle),
{ type: 'url', style: linkStyle, onPress: this.onUrlPress },
{ type: 'phone', style: linkStyle, onPress: this.onPhonePress },
{ type: 'email', style: linkStyle, onPress: this.onEmailPress },
]}
childrenProps={{ ...this.props.textProps }}
>
{this.props.isGroup ? (
<Text>
{parts.map(({ text, partType, data }, index) =>
partType ? (
<Text
key={`${index}-${data?.trigger ?? 'pattern'}`}
style={[
styles[this.props.position].textMention,
styles[this.props.position].mentionMe(
formatPhone(data.id) === ChatFunctions.phoneNumber
),
]}
onPress={() =>
this.props.onPressMenstion &&
this.props.onPressMenstion(data.id)
}
>
{`${data?.trigger}${mapNameWithLocalContact({
phone: data?.id,
name: data?.name,
})}`}
</Text>
) : (
<Text
key={index}
style={[
styles[this.props.position].text,
this.props.textStyle &&
this.props.textStyle[this.props.position],
this.props.customTextStyle,
]}
>
{text}
</Text>
)
)}
</Text>
) : (
this.props.currentMessage.text
)}
</ParsedText>
</View>
);
}
}
My expected style
I cannot use view to wrap this text because my text component is wrap by other text component
I've worked on it on snack you can check out this link and make sure you wrap those text with a View and use
flexDirection: 'row';
alignItems: 'center';
So to stop the View from filling the screen 100% add
alignSelf: 'start';
Checkout this link to see the code I've written for this
https://snack.expo.dev/#rajibola/spontaneous-beef-jerky
For TextStyle, borderTopRightRadius, borderTopLeftRadius, borderBottomRightRadius, borderBottomLeftRadius don't work. Only borderRadius works.
Maybe it's a bug!
as i am new in react native. i have no much knowledge of class component. i was stuck in code as class components are used in this code but i want to convert them into functional components. anyone please help me to convert this given code into functional component. this is a code of a swipeable card in react native all the given code in class component and use of constructor and this. i want to just convert it into functional component.
//This is an example of Tinder like Swipeable Card//
import React, { Component } from 'react';
//import react in our code.
import {
Platform, StyleSheet, View, Text,
Dimensions, Animated, PanResponder,
} from 'react-native';
//import all the components we are going to use.
const SCREEN_WIDTH = Dimensions.get('window').width;
class SwipeableCard extends React.Component {
constructor() {
super();
this.panResponder;
this.state = {
Xposition: new Animated.Value(0),
RightText: false,
LeftText: false,
};
this.Card_Opacity = new Animated.Value(1);
this.panResponder = PanResponder.create({
onStartShouldSetPanResponder: (evt, gestureState) => false,
onMoveShouldSetPanResponder: (evt, gestureState) => true,
onStartShouldSetPanResponderCapture: (evt, gestureState) => false,
onMoveShouldSetPanResponderCapture: (evt, gestureState) => true,
onPanResponderMove: (evt, gestureState) => {
this.state.Xposition.setValue(gestureState.dx);
if (gestureState.dx > SCREEN_WIDTH - 250) {
this.setState({
RightText: true,
LeftText: false,
});
} else if (gestureState.dx < -SCREEN_WIDTH + 250) {
this.setState({
LeftText: true,
RightText: false,
});
}
},
onPanResponderRelease: (evt, gestureState) => {
if (
gestureState.dx < SCREEN_WIDTH - 150 &&
gestureState.dx > -SCREEN_WIDTH + 150
) {
this.setState({
LeftText: false,
RightText: false,
});
Animated.spring(
this.state.Xposition,
{
toValue: 0,
speed: 5,
bounciness: 10,
},
{ useNativeDriver: true }
).start();
} else if (gestureState.dx > SCREEN_WIDTH - 150) {
Animated.parallel(
[
Animated.timing(this.state.Xposition, {
toValue: SCREEN_WIDTH,
duration: 200,
}),
Animated.timing(this.Card_Opacity, {
toValue: 0,
duration: 200,
}),
],
{ useNativeDriver: true }
).start(() => {
this.setState({ LeftText: false, RightText: false }, () => {
this.props.removeCard();
});
});
} else if (gestureState.dx < -SCREEN_WIDTH + 150) {
Animated.parallel(
[
Animated.timing(this.state.Xposition, {
toValue: -SCREEN_WIDTH,
duration: 200,
}),
Animated.timing(this.Card_Opacity, {
toValue: 0,
duration: 200,
}),
],
{ useNativeDriver: true }
).start(() => {
this.setState({ LeftText: false, RightText: false }, () => {
this.props.removeCard();
});
});
}
},
});
}
render() {
const rotateCard = this.state.Xposition.interpolate({
inputRange: [-200, 0, 200],
outputRange: ['-20deg', '0deg', '20deg'],
});
return (
<Animated.View
{...this.panResponder.panHandlers}
style={[
styles.card_Style,
{
backgroundColor: this.props.item.backgroundColor,
opacity: this.Card_Opacity,
transform: [
{ translateX: this.state.Xposition },
{ rotate: rotateCard },
],
},
]}>
<Text style={styles.Card_Title}> {this.props.item.card_Title} </Text>
{this.state.LeftText ? (
<Text style={styles.Left_Text_Style}> Left Swipe </Text>
) : null}
{this.state.RightText ? (
<Text style={styles.Right_Text_Style}> Right Swipe </Text>
) : null}
</Animated.View>
);
}
}
export default class App extends React.Component {
constructor() {
super();
this.state = {
Sample_Card_Array: [{
id: '1', card_Title: 'Card 1', backgroundColor: '#FFC107',
}, {
id: '2', card_Title: 'Card 2', backgroundColor: '#ED2525',
}, {
id: '3', card_Title: 'Card 3', backgroundColor: '#E7088E',
}, {
id: '4', card_Title: 'Card 4', backgroundColor: '#00BCD4',
}, {
id: '5', card_Title: 'Card 5', backgroundColor: '#FFFB14',
}],
No_More_Card: false,
};
}
componentDidMount() {
this.setState({
Sample_Card_Array: this.state.Sample_Card_Array.reverse(),
});
if (this.state.Sample_Card_Array.length == 0) {
this.setState({ No_More_Card: true });
}
}
removeCard = id => {
this.state.Sample_Card_Array.splice(
this.state.Sample_Card_Array.findIndex(x => x.id == id),
1
);
this.setState({ Sample_Card_Array: this.state.Sample_Card_Array }, () => {
if (this.state.Sample_Card_Array.length == 0) {
this.setState({ No_More_Card: true });
}
});
};
render() {
return (
<View style={styles.MainContainer}>
{this.state.Sample_Card_Array.map((item, key) => (
<SwipeableCard
key={key}
item={item}
removeCard={this.removeCard.bind(this, item.id)}
/>
))}
{this.state.No_More_Card ? (
<Text style={{ fontSize: 22, color: '#000' }}>No Cards Found.</Text>
) : null}
</View>
);
}
}
const styles = StyleSheet.create({
MainContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
paddingTop: Platform.OS === 'ios' ? 20 : 0,
},
card_Style: {
width: '75%',
height: '45%',
justifyContent: 'center',
alignItems: 'center',
position: 'absolute',
borderRadius: 7,
},
Card_Title: {
color: '#fff',
fontSize: 24,
},
Left_Text_Style: {
top: 22,
right: 32,
position: 'absolute',
color: '#fff',
fontSize: 20,
fontWeight: 'bold',
backgroundColor: 'transparent',
},
Right_Text_Style: {
top: 22,
left: 32,
position: 'absolute',
color: '#fff',
fontSize: 20,
fontWeight: 'bold',
backgroundColor: 'transparent',
},
});
the part in the render method is what you return.
to create stateObjects in functional components you will need to use the useState method
const functionalComponent = (props)=>{//props are passed in via props arg...
const defaultState = Xposition: new Animated.Value(0),
RightText: false,
LeftText: false
}
const [state,setState] = useState(defaultState);
... // more stuff
return (
<Animated.View
{...this.panResponder.panHandlers}
style={[
styles.card_Style,
{
backgroundColor: props.item.backgroundColor,
opacity: Card_Opacity,
transform: [
{ translateX: state.Xposition },
{ rotate: rotateCard },
],
},
]}>
<Text style={styles.Card_Title}> {props.item.card_Title} </Text>
{this.state.LeftText ? (
<Text style={styles.Left_Text_Style}> Left Swipe </Text>
) : null}
{this.state.RightText ? (
<Text style={styles.Right_Text_Style}> Right Swipe </Text>
) : null}
</Animated.View>
);
}
you should really go watch some videos on useState, you can be much more granular
to set the state you will need to use the setState method returned from the useState call : setState({..state,{XPosition:55}) or something ... you do the ...state to include the old state values, as the state variable will be overwritten with exactly what you pass in... it wont "update" the existing state it will overwrite it
the next bit is hooking into the functionality in componentDidMount you can do this with useEffect
useEffect(()=>{ // this is setup
// do the stuff from componentDidMount
return ()=>{
// any required teardown can be done here
},[] //[] signifies only do this when component mounts... not every update
);// end useEffect componentDidMount
again there is alot more to useEffect, if you want to do stuff when specific state or props are updated
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
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"
},
I am writing to create a todo application using react native and firebase, I followed up a youtube to develop an application that saves to file instead of firebase, but read up to include firebase in the application but I don't know how to bind the data to it and ensure until the submit button is clicked before it saves to the data base and display it on the page.
import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
TextInput,
ScrollView,
TouchableOpacity
} from 'react-native';
import Note from './Note';
import firebase from 'firebase';
export default class Main extends Component {
constructor(props){
super(props);
this.state = {
noteArray: [],
noteText: '',
};
}
componentWillMount() {
var config = {
apiKey: "AIzaSyAB3bO5C7pcLYv745DwwPqUicAshRTdzYk",
authDomain: "mytodo-6b198.firebaseapp.com",
databaseURL: "https://mytodo-6b198.firebaseio.com",
projectId: "mytodo-6b198",
storageBucket: "",
messagingSenderId: "314761285731"
};
firebase.initializeApp(config);
//console.log(firebase);
firebase.database().ref('todo/001').set(
{
note: this.state.noteText,
name: "Tola"
}
).then(() =>{
console.log('inserted');
}).catch((error) =>{
console.log(error);
});
}
render() {
let notes = this.state.noteArray.map((val, key)=>{
return <Note key={key} keyval={key} val={val}
deleteMethod={()=>this.deleteNote(key)}/>
});
return (
<View style={styles.container}>
<View style={styles.header}>
<Text style={styles.headerText}>Todo App</Text>
</View>
<ScrollView style={styles.scrollContainer}>
{notes}
</ScrollView>
<View style={styles.footer}>
<TextInput
style={styles.textInput}
placeholder='>note'
onChangeText={(noteText)=> this.setState({noteText})}
value={this.state.noteText}
placeholderTextColor='white'
underlineColorAndroid='transparent'>
</TextInput>
</View>
<TouchableOpacity onPress={ this.addNote.bind(this) } style={styles.addButton}>
<Text style={styles.addButtonText}>+</Text>
</TouchableOpacity>
</View>
);
}
addNote(){
if(this.state.noteText){
var d = new Date();
this.state.noteArray.push({
'date':d.getFullYear()+
"/"+(d.getMonth()+1) +
"/"+ d.getDate(),
'note': this.state.noteText
});
this.setState({ noteArray: this.state.noteArray });
this.setState({noteText:''});
}
}
deleteNote(key){
this.state.noteArray.splice(key, 1);
this.setState({noteArray: this.state.noteArray});
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
header: {
backgroundColor: '#E91E63',
alignItems: 'center',
justifyContent:'center',
borderBottomWidth: 10,
borderBottomColor: '#ddd'
},
headerText: {
color: 'white',
fontSize: 18,
padding: 26
},
scrollContainer: {
flex: 1,
marginBottom: 100
},
footer: {
position: 'absolute',
bottom: 0,
left: 0,
right: 0,
zIndex: 10
},
textInput: {
alignSelf: 'stretch',
color: '#fff',
padding: 20,
backgroundColor: '#252525',
borderTopWidth:2,
borderTopColor: '#ededed',
marginBottom: 30
},
addButton: {
position: 'absolute',
zIndex: 11,
right: 20,
bottom: 90,
backgroundColor: '#E91E63',
width: 70,
height: 70,
borderRadius: 35,
alignItems: 'center',
justifyContent: 'center',
elevation: 8
},
addButtonText: {
color: '#fff',
fontSize: 24
}
});
And there is a video tutorial to learn CRUD in native react, firebase and context API. I will be glad to watch one. Thank you
Note.js
import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
TouchableOpacity,
} from 'react-native';
export default class Note extends Component {
render() {
return (
<View key={this.props.keyval} style={styles.note}>
<Text style={styles.noteText}>{this.props.val.date}</Text>
<Text style={styles.noteText}>{this.props.val.note}</Text>
<TouchableOpacity onPress={this.props.deleteMethod} style={styles.noteDelete}>
<Text style={styles.noteDeleteText}>D</Text>
</TouchableOpacity>
</View>
);
}
}
You need to create the function for creating the payload and saving data. I recommend you to use arrow functions and a promise for asynchronous task. Try this and let me know if it helped you.
import React, {
Component
} from 'react';
import {
View,
Text,
StyleSheet,
TextInput,
ScrollView,
TouchableOpacity
} from 'react-native';
import Note from './Note';
// in the future i would recommend you to use react-native-firebase.
//but for learning purposes it's ok.
import firebase from 'firebase';
export default class Main extends Component {
constructor(props){
super(props);
this.state = {
noteArray: [],
noteText: '',
};
}
componentWillMount() {
var config = {
apiKey: "AIzaSyAB3bO5C7pcLYv745DwwPqUicAshRTdzYk",
authDomain: "mytodo-6b198.firebaseapp.com",
databaseURL: "https://mytodo-6b198.firebaseio.com",
projectId: "mytodo-6b198",
storageBucket: "",
messagingSenderId: "314761285731"
};
firebase.initializeApp(config);
// end of componentWillMount
}
// create ALL needed functions
// ist an arrow function
createNote = () => {
//create a promise for waiting until element is succesfully created
return new Promise((resolve, reject) => {
//extract current states
const { noteArray, noteText } = this.state
//create newElement
var d = new Date();
const newElement = {
'date':d.getFullYear()+ "/"+(d.getMonth()+1) + "/"+ d.getDate(),
'note': noteText
}
//set all states
this.setState({
noteArray: [...noteArray, newElement ], //correct array-state manipulation
noteText:''
}, () => resolve(newElement)) //new element ist passed as params to next then
})
}
_addNoteToFirebase = () => {
//this is an arrow function.
//myfunc = (params) => { /*custom logic*/}
const refInDatabase = firebase.database().ref('todo/001');
this.createNote()
.then((elementRecived) => refInDatabase.update(elementRecived))
.then(() => console.log('inserted'))
.catch((error) => console.log(error));
}
deleteNote = (key) => {
const { noteArray } = this.state
this.setState({
noteArray: noteArray.splice(key, 1)
})
}
// here is where render method starts
render() {
let notes = this.state.noteArray.map((val, key)=>{
return <Note
key={key}
keyval={key}
val={val}
deleteMethod={() => deleteNote(key)}
/>
});
return (
<View style={styles.container}>
<View style={styles.header}>
<Text style={styles.headerText}>Todo App</Text>
</View>
<ScrollView style={styles.scrollContainer}>
{notes}
</ScrollView>
<View style={styles.footer}>
<TextInput
style={styles.textInput}
placeholder='>note'
onChangeText={(noteText)=> this.setState({noteText})}
value={this.state.noteText}
placeholderTextColor='white'
underlineColorAndroid='transparent'>
</TextInput>
</View>
<TouchableOpacity onPress={this._addNoteToFirebase} style={styles.addButton}>
<Text style={styles.addButtonText}>+</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
header: {
backgroundColor: '#E91E63',
alignItems: 'center',
justifyContent:'center',
borderBottomWidth: 10,
borderBottomColor: '#ddd'
},
headerText: {
color: 'white',
fontSize: 18,
padding: 26
},
scrollContainer: {
flex: 1,
marginBottom: 100
},
footer: {
position: 'absolute',
bottom: 0,
left: 0,
right: 0,
zIndex: 10
},
textInput: {
alignSelf: 'stretch',
color: '#fff',
padding: 20,
backgroundColor: '#252525',
borderTopWidth:2,
borderTopColor: '#ededed',
marginBottom: 30
},
addButton: {
position: 'absolute',
zIndex: 11,
right: 20,
bottom: 90,
backgroundColor: '#E91E63',
width: 70,
height: 70,
borderRadius: 35,
alignItems: 'center',
justifyContent: 'center',
elevation: 8
},
addButtonText: {
color: '#fff',
fontSize: 24
}
});