Not able to refer to drawer layout in react native - react-native

I have my Js file like this.
"use strict"
var React = require('react-native')
var {
AppRegistry,
Component,
StyleSheet,
Text,
View,
TouchableNativeFeedback,
Image,
DrawerLayoutAndroid,
Navigator,
ListView,
ToolbarAndroid
} = React;
var ToolbarAndroid = require('ToolbarAndroid');
var Drawer = require('react-native-drawer');
import Screen2 from './Screen2';
import Screen3 from './Screen3';
class Screen1 extends Component {
openDrawer(){
this.refs['DRAWER'].openDrawer()
}
_handlePress(screen_name,loggedIn) {
this.refs.DRAWER.closeDrawer(),
this.refs.navigator.push(
{id: screen_name,
})
}
renderScene(route, navigator) {
switch(route.id){
case 'Screen1': return (
DrawerLayoutAndroid
drawerWidth={300}
ref={'DRAWER'}
drawerPosition={DrawerLayoutAndroid.positions.Left}
renderNavigationView={() => navigationView}>
<View style={styles.container}>
<ToolbarAndroid
navIcon={require('image!ic_menu_white')}
titleColor="white"
style={styles.toolbar}
onIconClicked={() => this.openDrawer()}
onActionSelected={this.onActionSelected} />
</View>
<ListView contentContainerStyle={styles.list}
dataSource={this.state.dataSource}
renderRow={this.renderItem.bind(this)}
/>
</DrawerLayoutAndroid>
);
case 'Screen2': return (<Screen2 navigator={navigator} />)
case 'Screen3': return (<Screen3 navigator={navigator} />)
}
}
render(){
navigationView = (
<View style={styles.header}>
<View style={styles.HeadingContainer}>
<TouchableNativeFeedback>
<View style={styles.HeadingItem}>
<Text style={styles.menuText}>
Welcome!
</Text>
<Text style={styles.menuText}>
Guest
</Text>
</View>
</TouchableNativeFeedback>
</View>
<View style={{flex: 4, backgroundColor: 'white'}}>
<TouchableNativeFeedback onPress={this._handlePress.bind(this,'Screen1')}>
<View style={styles.menuContainer}>
<Text style={styles.menu}>Albums</Text>
<Image
source={require('image!ic_menu_arrow')}
style={{flex : 1,width: 10, height: 10, margin: 20}} />
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback onPress={this._handlePress.bind(this,'Screen2')}>
<View style={styles.menuContainer}>
<Text style={styles.menu}>Member Validation</Text>
<Image
source={require('image!ic_menu_arrow')}
style={{flex : 1,width: 10, height: 10, margin: 20}} />
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback onPress={this._handlePress.bind(this,'Screen3')}>
<View style={styles.menuContainer}>
<Text style={styles.menu}>Settings</Text>
<Image
source={require('image!ic_menu_arrow')}
style={{flex : 1,width: 10, height: 10, margin: 20}} />
</View>
</TouchableNativeFeedback>
</View>
</View>
);
return(
<
<Navigator
initialRoute={{id: 'Screen1'}}
renderScene={this.renderScene.bind(this)}
ref='navigator'
configureScene={(route) => {
if (route.sceneConfig) {
return route.sceneConfig;
}
return Navigator.SceneConfigs.FloatFromRight;
}} />
);
}
}
var styles = StyleSheet.create({
list: {
justifyContent: 'center',
flexDirection: 'row',
flexWrap: 'wrap'
},
renderLoading: {
padding: 30,
marginTop: 65,
alignItems: 'center'
},
container: {
flexDirection: 'column',
backgroundColor: '#FAFAFA',
},
backgroundImage: {
flex: 1,
resizeMode: 'cover', // or 'stretch'
},
rightContainer: {
flex: 1,
},
year: {
textAlign: 'center',
},
thumbnail: {
width: 53,
height: 81,
},
listView: {
paddingTop: 20,
backgroundColor: '#F5FCFF',
margin:20
},
movie: {
height: 150,
flex: 1,
alignItems: 'center',
flexDirection: 'column',
},
titles: {
fontSize: 10,
marginBottom: 8,
width: 90,
textAlign: 'center',
},
header: {
flex: 1,
flexDirection: 'column',
},
menuContainer: {
flexDirection: 'row',
},
HeadingItem: {
flex: 1,
flexDirection: 'column',
alignItems: 'center',
padding: 10,
},
HeadingContainer: {
flex: 1,
backgroundColor: '#00a2ed',
},
menuText: {
fontSize: 14,
color: 'black',
},
menu: {
flex: 4,
fontSize: 12,
color: 'black',
margin: 20,
},
toolbar: {
backgroundColor: '#00a2ed',
height: 56,
},
});
export default Screen1;
Now I am not able to refer to Drawer reference variable 'DRAWER'.It gives me error undefined is not an object.Not able to open or close drawer.
I want DrawerLayout for Screen1 only so I am rendering it in RenderScene method.
If i implement DrawerLayout in render method,then I am able to refer to reference Drawer.
Can we create reference in render method only.IF yes how to solve this problem.

Accessing drawer object using state object of component.
"use strict"
var React = require('react-native')
var {
AppRegistry,
Component,
StyleSheet,
Text,
View,
TouchableNativeFeedback,
Image,
DrawerLayoutAndroid,
Navigator,
ListView,
ToolbarAndroid
} = React;
var ToolbarAndroid = require('ToolbarAndroid');
var Drawer = require('react-native-drawer');
import Screen2 from './Screen2';
import Screen3 from './Screen3';
class Screen1 extends Component {
constructor(props) {
super(props);
this.state = {
drawer: null,
};
}
setDrawer = (drawer) => {
this.setState({
drawer
});
};
openDrawer(){
this.state.drawer.openDrawer()
}
_handlePress(screen_name,loggedIn) {
this.state.drawer.closeDrawer(),
this.refs.navigator.push(
{id: screen_name,
})
}
renderScene(route, navigator) {
switch(route.id){
case 'Screen1':
const { drawer } = this.state;
return (
<DrawerLayoutAndroid
drawerWidth={300}
ref={(drawer) => { !this.state.drawer ? this.setDrawer(drawer) : null }}
drawerPosition={DrawerLayoutAndroid.positions.Left}
renderNavigationView={() => navigationView}>
<View style={styles.container}>
<ToolbarAndroid
navIcon={require('image!ic_menu_white')}
titleColor="white"
style={styles.toolbar}
onIconClicked={() => this.openDrawer()}
onActionSelected={this.onActionSelected} />
</View>
<ListView contentContainerStyle={styles.list}
dataSource={this.state.dataSource}
renderRow={this.renderItem.bind(this)}
/>
</DrawerLayoutAndroid>
);
case 'Screen2': return (<Screen2 navigator={navigator} />)
case 'Screen3': return (<Screen3 navigator={navigator} />)
}
}
render(){
navigationView = (
<View style={styles.header}>
<View style={styles.HeadingContainer}>
<TouchableNativeFeedback>
<View style={styles.HeadingItem}>
<Text style={styles.menuText}>
Welcome!
</Text>
<Text style={styles.menuText}>
Guest
</Text>
</View>
</TouchableNativeFeedback>
</View>
<View style={{flex: 4, backgroundColor: 'white'}}>
<TouchableNativeFeedback onPress={this._handlePress.bind(this,'Screen1')}>
<View style={styles.menuContainer}>
<Text style={styles.menu}>Albums</Text>
<Image
source={require('image!ic_menu_arrow')}
style={{flex : 1,width: 10, height: 10, margin: 20}} />
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback onPress={this._handlePress.bind(this,'Screen2')}>
<View style={styles.menuContainer}>
<Text style={styles.menu}>Member Validation</Text>
<Image
source={require('image!ic_menu_arrow')}
style={{flex : 1,width: 10, height: 10, margin: 20}} />
</View>
</TouchableNativeFeedback>
<TouchableNativeFeedback onPress={this._handlePress.bind(this,'Screen3')}>
<View style={styles.menuContainer}>
<Text style={styles.menu}>Settings</Text>
<Image
source={require('image!ic_menu_arrow')}
style={{flex : 1,width: 10, height: 10, margin: 20}} />
</View>
</TouchableNativeFeedback>
</View>
</View>
);
return(
<
<Navigator
initialRoute={{id: 'Screen1'}}
renderScene={this.renderScene.bind(this)}
ref='navigator'
configureScene={(route) => {
if (route.sceneConfig) {
return route.sceneConfig;
}
return Navigator.SceneConfigs.FloatFromRight;
}} />
);
}
}
var styles = StyleSheet.create({
list: {
justifyContent: 'center',
flexDirection: 'row',
flexWrap: 'wrap'
},
renderLoading: {
padding: 30,
marginTop: 65,
alignItems: 'center'
},
container: {
flexDirection: 'column',
backgroundColor: '#FAFAFA',
},
backgroundImage: {
flex: 1,
resizeMode: 'cover', // or 'stretch'
},
rightContainer: {
flex: 1,
},
year: {
textAlign: 'center',
},
thumbnail: {
width: 53,
height: 81,
},
listView: {
paddingTop: 20,
backgroundColor: '#F5FCFF',
margin:20
},
movie: {
height: 150,
flex: 1,
alignItems: 'center',
flexDirection: 'column',
},
titles: {
fontSize: 10,
marginBottom: 8,
width: 90,
textAlign: 'center',
},
header: {
flex: 1,
flexDirection: 'column',
},
menuContainer: {
flexDirection: 'row',
},
HeadingItem: {
flex: 1,
flexDirection: 'column',
alignItems: 'center',
padding: 10,
},
HeadingContainer: {
flex: 1,
backgroundColor: '#00a2ed',
},
menuText: {
fontSize: 14,
color: 'black',
},
menu: {
flex: 4,
fontSize: 12,
color: 'black',
margin: 20,
},
toolbar: {
backgroundColor: '#00a2ed',
height: 56,
},
});
export default Screen1;

The best and easy solution of your problem is make separate file for Navigating different scenes which contains only Navigator component, there you can navigate different scenes with suitable condition.
Make different files as:
1. navigator.js
2. screen1.js
3. screen2.js
in navigator.js keep the code as
<Navigator
initialRoute={{id: 'Screen1'}}
renderScene={this.renderScene.bind(this)}
ref='navigator'
configureScene={(route) => {
if (route.sceneConfig) {
return route.sceneConfig;
}
return Navigator.SceneConfigs.FloatFromRight;
}} />
also do switch case statement here:
renderScene(route, navigator) {
switch(route.id){
case 'Screen1': return (<Screen1 navigator={navigator}>
);
case 'Screen2': return (<Screen2 navigator={navigator} />)
case 'Screen3': return (<Screen3 navigator={navigator} />)
}
Then make individual component of screen1, screen2, screen3 and place all components like
<DrawerLayout><Toolbar/><ListView/></DrawerLayout>
in which screen you want in their respective render() function, also you can call openDrawer() like function in your specific screen.
This way you can reduced your messy code organization and complete your code.
Hope this will help your problem.

Related

How to show different tags, depending on the user logged. Expo react

I need to show different tags depending on which user is logged.
Franchisee will see: 'Central' 'Empleados' 'Clientes'.
Employee: 'Store' 'Clientes'
User: none. just the generic info.
Here is my code:
(this is the array that states the scrollview)
const Chats = (props) => {
const TAGS = [
"store",
"Clientes",
"Central",
"Empleados",
]
and this is the component:
import React, { useState } from "react";
import { StyleSheet, FlatList, TouchableOpacity, ScrollView, Image } from 'react-native';
import { SimpleHeader, View, Text } from '../../elements/index';
const Chatstores = ({ chatsstore, navigation }) => (
<View>
<TouchableOpacity onPress={() => navigation.navigate("ChatPersonal")}>
<View style={styles.list} >
<Image source={chatsstore.img} style={styles.iconimg} />
<View style={styles.dataText}>
<View style={styles.nametime}>
<Text style={styles.text}>{chatsstore.name} </Text>
<Text >{chatsstore.time}</Text>
</View>
<Text style={styles.msg}>{chatsstore.msg} </Text>
</View>
</View>
</TouchableOpacity>
</View>
);
const ChatClients = ({ chatsClients, navigation }) => (
<View>
<TouchableOpacity onPress={() => navigation.navigate("ChatPersonal")}>
<View style={styles.list}>
<Image source={chatsClients.img} style={styles.iconimg} />
<View style={styles.dataText}>
<View style={styles.nametime}>
<Text style={styles.text}>{chatsClients.name} </Text>
<Text >{chatsClients.time}</Text>
</View>
<Text style={styles.msg}>{chatsClients.msg} </Text>
</View>
</View>
</TouchableOpacity>
</View>
);
const Chats = (props) => {
const { TAGS, chatsstore, chatsClients, navigation } = props;
const [selectedTag, setSelectedTag] = useState(null)
const [routeDistance, setRouteDistance] = useState(0);
return (
<View style={styles.wrapper}>
<SimpleHeader
style={styles.head}
titleLeft="Chats"
onSearchPress
onAddPress
/>
{/**shows horizontal, scrollview of Tags. */}
<View style={styles.scrollview}>
<ScrollView horizontal showsHorizontalScrollIndicator={false} >
<View style={styles.viewcontainer}>
{TAGS.map((tag) => (
<TouchableOpacity
onPress={() =>
setSelectedTag(tag === selectedTag ? null : tag)
}>
<View
style={[
styles.tag,
selectedTag === tag ? styles.selectedTag : {}
]}>
<Text style={styles.textTag}>{tag}</Text>
</View>
</TouchableOpacity>
))}
</View>
</ScrollView>
</View>
{/**If tag is store, shows its data, otherwise the rest */}
{selectedTag === "store" ? (
<View style={styles.chat}>
<FlatList
data={chatsstore}
renderItem={({ item, index }) => (
<Chatstores
chatsstore={item}
index={index}
navigation={navigation}
/>
)}
keyExtractor={(chatsstore) => chatsstore.name}
ListEmptyComponent={() => (
<Text center bold>No hay ningún mensaje de clientes</Text>
)}
/>
</View>
) :
<View style={styles.chat}>
<FlatList
data={chatsClients}
renderItem={({ item, index }) => (
<ChatClients
chatsClients={item}
index={index}
navigation={navigation}
/>
)}
keyExtractor={(chatsClients) => chatsClients.name}
ListEmptyComponent={() => (
<Text center bold>No hay ningún mensaje de clientes</Text>
)}
/>
</View>
}
</View>
);
};
const styles = StyleSheet.create({
wrapper: {
backgroundColor: "#ffffff",
display: "flex",
flex: 1,
},
head: {
height: 80,
display: "flex",
alignItems: "center",
zIndex: 1,
top: 5,
},
scrollview: {
display: "flex",
alignItems: "center",
justifyContent: "space-evenly",
},
viewcontainer: {
display: "flex",
flexDirection: "row",
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 2,
},
shadowOpacity: 0.25,
shadowRadius: 3.84,
elevation: 1,
right: 10,
},
list: {
bottom: 15,
flexWrap: "wrap",
alignContent: "space-between",
position: "relative",
marginVertical: 2,
backgroundColor: "#fff",
shadowColor: "#000",
elevation: 2,
flexDirection: "row",
}, dataText: {
alignSelf: "center",
flexDirection: "column",
width: "80%",
},
nametime: {
display: "flex",
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
},
iconimg: {
display: "flex",
height: 43,
width: 43,
alignSelf: "center",
flexDirection: "column",
},
chat: {
margin: 10,
},
text: {
margin: 10,
fontFamily: "Montserrat_700Bold",
paddingHorizontal: 10,
},
msg: {
margin: 10,
fontFamily: "Montserrat_400Regular",
fontSize: 15,
paddingHorizontal: 10,
bottom: 10
},
map: {
display: "flex",
height: "100%",
},
tag: {
display: "flex",
alignSelf: "center",
marginBottom: 1,
width: 225,
padding: 10,
},
selectedTag: {
borderBottomColor: '#F5BF0D',
borderBottomWidth: 2,
},
textTag: {
fontFamily: "Montserrat_700Bold",
alignItems: "center",
textAlign: "center",
fontSize: 15,
},
buttonContainer: {
marginHorizontal: 20
},
button: {
backgroundColor: "#000000",
top: Platform.OS === 'ios' ? 12 : 20,
height: 60,
marginBottom: 40,
marginRight: 10,
},
});
export default Chats;
So I guess that in my "show horizontal tags" I should write some kind of if, that gets the role from the user token?
Or would it be better to write different routes into the navigation and handle it in 3 different components?

How to send Selected Custom Checkbox data to next page in react native?

Here I have created toggle custom checkboxes and those are rendered within FlatList with Name.
Now which checkboxes are checked i want to send those names into next screen using navigation.
So how can i implement that functionality, if anyone knows then please help me for the same.
/**Code For custom checkbox:**/
import React from "react";
import {
TouchableOpacity,
Image,
View,
SafeAreaView,
Text,
} from "react-native";
import { useState } from "react";
import IconAntDesign from "react-native-vector-icons/AntDesign";
export function CheckBoxCustom() {
const [count, setCount] = useState(0);
return (
<SafeAreaView>
<TouchableOpacity
style={{
backgroundColor: "white",
width: 20,
height: 20,
borderWidth: 2,
borderColor: "#ddd",
}}
onPress={() => setCount(!count)}
>
{count ? (
<IconAntDesign name="check" size={15} color={"black"} />
) : null}
</TouchableOpacity>
</SafeAreaView>
);
}
/**Code for FlatList:**/
import React, {useState} from 'react';
import {
SafeAreaView,
Text,
View,
TouchableOpacity,
Image,
StyleSheet,
FlatList,
Dimensions,
useWindowDimensions,
ScrollView,
Button,
} from 'react-native';
import Header from '../CustomComponents/RestaurentUI/Header';
import {CheckBoxCustom} from '../CustomComponents/RestaurentUI/Checkbox';
import {TextInput} from 'react-native-gesture-handler';
import {TabView, SceneMap, TabBar} from 'react-native-tab-view';
import {NavigationContainer, useNavigation} from '#react-navigation/native';
import GetCheckBoxData from './GetCheckBoxData';
const data = [
{
name: 'Lumlère brûlée',
status: 'Problems',
},
{
name: 'Aucune eau chaude',
status: 'Problems',
},
{
name: 'Lumlère brûlée',
status: 'Problems',
},
{
name: 'Service de ménage',
status: 'Problems',
},
{
name: 'AC non-fonctionnel',
status: 'Problems',
},
{
name: 'WIFI non-fonctionnel',
status: 'Problems',
},
{
name: 'Four non-fonctionnel',
status: 'Problems',
},
];
const renderItem = ({item, index}) => {
return (
<View>
<View style={{flexDirection: 'row'}}>
<CheckBoxCustom />
<Text style={{marginLeft: 10}}>{item.name} </Text>
</View>
</View>
);
};
const separator = () => {
return (
<View
style={{
height: 1,
backgroundColor: '#f1f1f1',
marginBottom: 12,
marginTop: 12,
}}
/>
);
};
const FirstRoute = () => (
<FlatList
style={{marginTop: 20}}
data={data}
keyExtractor={(e, i) => i.toString()}
renderItem={renderItem}
ItemSeparatorComponent={separator}
/>
);
const SecondRoute = () => (
<View style={[styles.scene, {backgroundColor: 'white'}]} />
);
const initialLayout = {width: Dimensions.get('window').width};
const renderScene = SceneMap({
first: FirstRoute,
second: SecondRoute,
});
const ReportScreen = ({navigation}) => {
const nav = useNavigation();
const layout = useWindowDimensions();
const [index, setIndex] = useState(0);
const [routes] = useState([
{key: 'first', title: 'Problemes'},
{key: 'second', title: 'Besoins complémentaitaires'},
]);
const goToScreen = () => {
navigation.navigate('GetCheckBoxData', {title: 'Hii all'});
};
const [checked, setChecked] = useState({});
const checkToggle = id => {
setChecked(checked => ({
...checked,
[id]: !checked[id],
}));
};
return (
<SafeAreaView style={styles.safearea}>
<Header title="Report" />
<ScrollView showsVerticalScrollIndicator={false} bounces={false}>
<View style={{flexDirection: 'row', marginTop: 20}}>
<View style={{flex: 1, height: 1, backgroundColor: '#ccc'}} />
</View>
<View style={styles.cardView}>
<View style={styles.subView}>
<Image
style={styles.image}
source={require('../Assets/UIPracticeImage/H1.jpg')}
/>
<View style={styles.internalSubView}>
<View style={styles.nameView}>
<Text style={styles.nameText}>Pine Hill Green Caban</Text>
</View>
<View style={styles.dateView}>
<Text style={styles.dateText}>May 22-27</Text>
</View>
</View>
</View>
</View>
<View style={{flexDirection: 'row'}}>
<View style={{flex: 1, height: 1, backgroundColor: '#ccc'}} />
</View>
<View
style={{
// backgroundColor: 'lime',
flex: 1,
height: 385,
width: '100%',
}}>
<TabView
navigationState={{index, routes}}
renderScene={renderScene}
onIndexChange={setIndex}
initialLayout={initialLayout}
style={styles.container}
renderTabBar={props => (
<TabBar
tabStyle={{alignItems: 'flex-start', width: 'auto'}}
{...props}
renderLabel={({route, color}) => (
<Text style={{color: 'black'}}>{route.title}</Text>
)}
style={{backgroundColor: 'white'}}
/>
)}
/>
</View>
<Button title="Click me" onPress={goToScreen} />
</ScrollView>
</SafeAreaView>
);
};
export default ReportScreen;
const styles = StyleSheet.create({
safearea: {
marginHorizontal: 20,
},
cardView: {
borderRadius: 10,
marginVertical: 10,
paddingVertical: 8,
},
subView: {
flexDirection: 'row',
},
image: {
height: 80,
width: 110,
borderRadius: 10,
},
internalSubView: {
justifyContent: 'space-between',
flex: 1,
},
nameView: {
justifyContent: 'space-between',
flexDirection: 'row',
alignItems: 'center',
marginLeft: 10,
},
nameText: {
fontWeight: 'bold',
width: '45%',
fontSize: 15,
},
dateView: {
flexDirection: 'row',
alignItems: 'center',
marginLeft: 10,
justifyContent: 'space-between',
},
dateText: {
width: 80,
},
listTab: {
flexDirection: 'row',
marginBottom: 20,
marginTop: 20,
},
btnTab: {
borderWidth: 3,
borderColor: 'white',
flexDirection: 'row',
marginRight: 10,
},
btnTabActive: {
borderWidth: 3,
borderBottomColor: '#fdd83d',
borderColor: 'white',
},
scheduleButton: {
backgroundColor: '#fdd83d',
alignItems: 'center',
paddingVertical: 15,
borderRadius: 10,
marginTop: 15,
},
container: {
marginTop: 20,
},
scene: {
flex: 1,
},
});
[![UI image][1]][1]
[1]: https://i.stack.imgur.com/AuLT8.png
You may want to lift the checkbox state to the parent component, i.e. make the checkboxes controlled, and collect the checked checkbox values. For this I'm assuming your data items have an id property, but any unique item property will suffice.
Example:
export function CheckBoxCustom({ checked, onPress }) {
return (
<SafeAreaView>
<TouchableOpacity
style={{
backgroundColor: "white",
width: 20,
height: 20,
borderWidth: 2,
borderColor: "#ddd",
}}
onPress={onPress}
>
{checked ?? <IconAntDesign name="check" size={15} color={"black"} />}
</TouchableOpacity>
</SafeAreaView>
);
}
...
const [checked, setChecked] = useState({});
const checkToggle = id => {
setChecked(checked => ({
...checked,
[id]: !checked[id],
}));
};
const renderItem = ({ item, index }) => {
return (
<View>
<View style={{ flexDirection: "row" }}>
<CheckBoxCustom
checked={checked[item.id]}
onPress={() => checkToggle(item.id)}
/>
<Text style={{ marginLeft: 10 }}>{item.name}</Text>
</View>
</View>
);
};
<FlatList
data={dataList}
keyExtractor={(e, i) => i.toString()}
renderItem={renderItem}
ItemSeparatorComponent={separator}
/>;
If your data hasn't any good GUID candidates then I suggest augmenting your data to include good GUIDs.
To pass the checked/selected items filter the dataList array.
Example:
const selected = dataList.filter(
item => checked[item.id]
);
// pass selected in navigation action

How to refresh the navigation parameters when there are more card components to navigate in React Native

When I click one card component and pass the data to the other page, and when I go back and click another one parameter that I pass from navigation, the navigate does not get changed. Here is my first page to navigate from:
import React,{ useState,useEffect} from 'react';
import { View, Text,TouchableOpacity, Button, StyleSheet ,Image,ScrollView} from 'react-native';
import { FontAwesome, Feather, MaterialIcons,Ionicons } from 'react-native-vector-icons';
const PaymentScreen = ({ route, navigation }) => {
const [paymentList, setPaymentList] = useState([]);
useEffect(() => {
fetch(
"https://run.mocky.io/v3/73958238-7761-4d81-8577-793ff92c0ea1"
)
.then((res) => res.json())
.then((data) => {
setPaymentList(data);
});
}, []);
const showPayment=() =>{
return (
paymentList &&
paymentList
.filter((word) => route.params.Name== word.userID)
.map((Aname, i) => {
return (
<View style={{padding: 8 }}>
<PaymenCard date={Aname.date} discount={Aname.id} cash={Aname.amount} forwardLink={() => navigation.navigate('morePayments',{itemId: Aname.id})}/>
</View>
);
})
)
}
return (
<View style={styles.container}>
<View style={styles.paymentbox}>
<Text style={styles.payment}>Payments</Text>
</View>
<ScrollView>
{ showPayment()}
</ScrollView>
</View>
);
};
export default PaymentScreen;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor:'#22343C',
},
payment:{
fontSize:42,
color: "white",
fontWeight: "bold",
},
paymentbox:{
marginLeft:32,
paddingBottom: 5
}
});
function PaymenCard(props ){
return(
<TouchableOpacity onPress={props.forwardLink}>
<View style={styles1.cardbox}>
<View style={styles1.square}>
<View style={styles1.dollarbig}>
<MaterialIcons name="monetization-on" color="#FFC542" size={30} />
</View>
</View>
<View style={styles1.datedisc}>
<View style={styles1.date}>
<Text style={styles1.datetext}>{props.date} </Text>
</View>
<View style={styles1.discount}>
<View style={styles1.rocket}>
<FontAwesome name="rocket" color="#FFC542" size={20} />
</View>
<View style={styles1.discountval}>
<Text style={styles1.discounttext}>{props.discount}</Text>
</View>
</View>
</View>
<View style={styles1.cashbox}>
<Text style={styles1.cashtext}>{props.cash}</Text>
</View>
</View>
</TouchableOpacity>
)
}
const styles1 = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#22343C',
},
cardbox: {
height: 115,
width: 345,
backgroundColor: '#30444E',
borderRadius: 25,
marginLeft: 22,
flexDirection: 'row',
},
square: {
height: 57,
width: 59,
borderRadius: 12,
backgroundColor: '#FF565E',
marginTop: 24,
marginLeft: 23,
},
dollarbig: {
marginTop: 15,
alignItems: 'center',
},
datedisc: {
marginTop: 24,
marginLeft: 16,
width: 145,
flexDirection:"column"
},
datetext: {
color: 'white',
fontSize: 14,
},
discount:{
marginTop:15,
flexDirection:"row",
},
rocket:{
},
discountval:{
marginLeft:13
},
discounttext:{
color:"white",
fontSize: 14,
},
cashbox:{
marginTop:30,
marginLeft:25
},
cashtext:{
color:"#FF575F",
fontWeight:"bold",
fontSize:18
}
});
I found the solution. there I have used initial params. so once the value is set it not going to upgrade again. I used react context API to set the updating values globally

Emailvalidator (require("email-validator") stopped working

I am doing email validation in my Signup form and all of a sudden it doesn't work anymore. I didn't change the signup.js file so it is a bit strange. I started working on the login.js file today so maybe there is some 'interference', but I don't have any idea where to look fist to be honest.
So here is the signup.js, where I put the emailvalidation that doesn't work anymore in bold.
import React, { Component } from 'react';
import { Text, StyleSheet, TouchableOpacity, Image, TextInput, View } from 'react-native';
import firebase from 'react-native-firebase';
var validator = require("email-validator");
export default class loginComponent extends Component {
constructor(props) {
super(props);
this.state = {firstName: ''};
this.state = {lastName: ''};
this.state = {email: ''};
this.state = {password: ''};
this.state = {emailValidated: false};
this.state = {errorMessage: null};
}
handleSignUp = () => {
firebase
.auth()
.createUserWithEmailAndPassword(this.state.email, this.state.password)
.then(() => this.props.navigation.navigate('Main'))
.catch(error => this.setState({ errorMessage: error.message }))
}
render() {
function renderEmailValidationState(emailInput) {
if(validator.validate(emailInput)) {
return false;
} else {
return true;
}
}
return (
<View style={styles.container}>
<View style={styles.logoContainer} >
<Image source={require('./assets/logo.png')} style={styles.logo}></Image>
<Text style={styles.slush}>
Lenen of huren, {"\n"} bij de buren!
</Text>
</View>
<View style={styles.formContainer}>
<View style={styles.inputTextFieldContainer}>
{this.state.errorMessage &&
<Text style={{ color: 'red' }}>
{this.state.errorMessage}
</Text>
}
<TextInput
style={styles.inputTextField}
placeholder="Enter you first name"
value={this.state.text}
backgroundColor="white"
onChangeText={(firstName) => this.setState({firstName})}
/>
<TextInput
style={styles.inputTextField}
placeholder="Enter you last name"
value={this.state.text}
backgroundColor="white"
onChangeText={(lastName) => this.setState({lastName})}
/>
<TextInput
style={styles.inputTextField}
placeholder="Enter your e-mail"
value={this.state.text}
backgroundColor="white"
onChangeText={(email) => this.setState({email})}
/>
<TextInput
style={styles.inputTextField}
placeholder="Enter your password"
value={this.state.password}
backgroundColor="white"
onChangeText={(password) => this.setState({password})}
/>
<TouchableOpacity
disabled= {renderEmailValidationState(this.state.email)}
style={styles.buttonContainer}
onPress={this.handleSignUp}
>
<View>
<Text style={styles.buttonText}>Sign up!</Text>
</View>
</TouchableOpacity>
<Text style={styles.plainText}>
Already a user?
</Text>
<TouchableOpacity
style={styles.buttonContainer}
onPress={() => this.props.navigation.navigate('Login')}
>
<View>
<Text style={styles.buttonText}>Login!</Text>
</View>
</TouchableOpacity>
</View>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 2,
padding:10,
backgroundColor:'#c6f1e7',
alignItems: 'stretch',
justifyContent: 'space-around'
},
logoContainer: {
padding: 10,
height: 250,
justifyContent: 'center' ,
alignItems: 'center'
},
logo: {
width: 250,
height: 250
},
slush: {
fontSize: 20,
color: '#59616e',
fontFamily: 'Raleway-Regular'
},
formContainer: {
flex:1,
padding: 10,
},
inputTextFieldContainer: {
padding: 100,
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: 30
},
inputTextField: {
padding: 10,
height: 40,
width: 300,
marginBottom: 10,
fontSize: 16,
fontFamily: 'Raleway-Regular',
},
buttonContainer: {
padding: 10,
marginBottom: 20,
width: 300,
alignItems: 'center',
backgroundColor: '#acdcd7',
},
buttonText: {
padding: 1,
fontSize: 16,
color: '#59616e',
fontFamily: 'Raleway-Regular',
},
plainText: {
padding: 1,
fontSize: 16,
marginBottom: 5,
fontFamily: 'Raleway-Regular',
color: '#59616e'
},
});
And this is the login.js, but that is work in progress.
import React, { Component } from 'react';
import { Text, StyleSheet, TouchableOpacity, Image, TextInput, View } from 'react-native';
import firebase from 'react-native-firebase';
var validator = require("email-validator");
export default class loginComponent extends Component {
constructor(props) {
super(props);
this.state = {email: ''};
this.state = {password: ''};
this.state = {emailValidated: false};
this.state = {errorMessage: null};
}
render() {
function renderEmailValidationState(emailInput) {
if(validator.validate(emailInput)) {
return false;
} else {
return true;
}
}
return (
<View style={styles.container}>
<View style={styles.logoContainer}>
<Image source={require('./assets/logo.png')} style={styles.logo}></Image>
<Text style={styles.slush}>
Huren bij de buren!
</Text>
</View>
<View style={styles.formContainer}>
<View style={styles.inputTextFieldContainer}>
{this.state.errorMessage &&
<Text style={{ color: 'red' }}>
{this.state.errorMessage}
</Text>
}
<TextInput
style={styles.inputTextField}
placeholder="Enter your e-mail"
value={this.state.text}
backgroundColor="white"
onChangeText={(email) => this.setState({email})}
/>
<TextInput
style={styles.inputTextField}
placeholder="Enter your password"
value={this.state.password}
backgroundColor="white"
onChangeText={(password) => this.setState({password})}
/>
<TouchableOpacity
**disabled= {renderEmailValidationState(this.state.email)}**
style={styles.buttonContainer}
onPress={this.handleSignUp}
>
<View>
<Text style={styles.buttonText}>Sign up!</Text>
</View>
</TouchableOpacity>
<Text style={styles.plainText}>
Don't have an account?
</Text>
<TouchableOpacity
style={styles.buttonContainer}
onPress={() => this.props.navigation.navigate('SignUp')}
>
<View>
<Text style={styles.buttonText}>Register!</Text>
</View>
</TouchableOpacity>
</View>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 2,
padding:10,
backgroundColor:'#c6f1e7',
alignItems: 'stretch',
justifyContent: 'space-around'
},
logoContainer: {
padding: 10,
height: 350,
justifyContent: 'center' ,
alignItems: 'center'
},
logo: {
width: 250,
height: 250
},
slush: {
fontSize: 25,
color: '#59616e',
fontFamily: 'Raleway-Regular'
},
formContainer: {
flex:1,
padding: 10,
},
inputTextFieldContainer: {
padding: 100,
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: 30
},
inputTextField: {
padding: 10,
height: 40,
width: 300,
marginBottom: 10,
fontSize: 16,
fontFamily: 'Raleway-Regular',
},
buttonContainer: {
padding: 10,
marginBottom: 20,
width: 300,
alignItems: 'center',
backgroundColor: '#acdcd7',
},
buttonText: {
padding: 1,
fontSize: 16,
color: '#59616e',
fontFamily: 'Raleway-Regular',
},
plainText: {
padding: 1,
fontSize: 16,
marginBottom: 5,
fontFamily: 'Raleway-Regular',
color: '#59616e'
},
});
Can anyone point me in the good direction?
Thanks a lot!
Tim
try this npm i raysk-vali
instead of email-validator.
usage:
const { isEmail } = require("raysk-vali");
isEmail("abc#example.com") // return true
isEmail("abcexample.com") // return false
for more checkout the documentation : https://www.npmjs.com/package/raysk-vali.

Error in React native snack

I don't understand the error message from the snack. "failed to install module ./assets/locales/sv.json..."
What does it mean? It seems to be this row that is failing:
// Import all locales
import en from './assets/locales/en.json';
import sv from './assets/locales/sv.json';
import he from './assets/locales/he.json';
import ar from './assets/locales/ar.json';
https://snack.expo.io/#niklasro/livejobb-snack
import React from 'react';
import { setLocale, strings, isoLangs } from './i18n.js';
import {Image, Picker, StyleSheet, ListView, Text, TextInput, TouchableHighlight, View} from 'react-native';
import {StackNavigator} from 'react-navigation'; // Version can be specified in package.json
import {Constants} from 'expo';
class HomeScreen extends React.Component {
state = {
language : '', itemValues: [], languages2: [], pickers: [], user: '',
username: 'Ivanka',
};
render() {
return (
<View style={styles.container}>
<View style={styles.section1}>
<Text style={[styles.text, {paddingBottom: 20}]}>{strings('login.welcome', { name: this.state.username })}</Text>
</View>
<View style={styles.section2}>
<Text style={[styles.text, {paddingTop: 20}]}>{strings('login.verified')}</Text>
</View>
<View style={styles.section3}>
<Text style={styles.text}>{strings('login.signup_as')}</Text>
</View>
<View style={styles.section4}>
<View style={styles.buttonContainer}>
<View style={styles.button}>
<TouchableHighlight onPress={() => this.props.navigation.navigate('Details')}>
<Image source={require('./assets/stck2.png')} style={styles.image}/>
</TouchableHighlight>
<TouchableHighlight onPress={() => this.props.navigation.navigate('Details')}>
<Text style={styles.buttonText}>{strings('login.translator')}</Text>
</TouchableHighlight>
</View>
<View style={styles.button}>
<TouchableHighlight onPress={() => this.props.navigation.navigate('Recruiter')}>
<Image source={require('./assets/stck1.png')} style={styles.image}/>
</TouchableHighlight>
<TouchableHighlight onPress={() => this.props.navigation.navigate('Recruiter')}>
<Text style={styles.buttonText}>{strings('login.recruiter')}</Text>
</TouchableHighlight>
</View>
</View>
<TouchableHighlight onPress={() =>{ setLocale('en'); this.setState({
dumme: 'dummy'
}); }}>
<Text style={styles.buttonText}>en</Text>
</TouchableHighlight>
<TouchableHighlight onPress={() => setLocale('sv')}>
<Text style={styles.buttonText}>sv</Text>
</TouchableHighlight>
</View>
</View>
);
}
}
class DetailsScreen extends React.Component {
constructor(props) {
super(props);
this.addLanguage = this.addLanguage.bind(this)
}
state = {
count: 0, itemValues: [], languages : [],languages2 : [], pickers: [], user: '',
username: 'Ivanka',
someVal: 'ar',
};
addLanguage() {
let pickers = this.state.pickers;
let count = this.state.count;
count++;
pickers.push(
{
id: 1,
color: "blue",
text: "text1"
}
);
let languages = this.state.languages;
languages.push('new');
this.setState({
count: count,
languages: languages,
});
let languages2 = this.state.languages2;
languages2.push('new');
this.setState({
count: count,
languages2: languages2,
});
}
update2(lang, ran, counter){
let languages2 = this.state.languages2;
languages2[counter]=lang;
this.setState({
languages2: languages2,
});
}
update(lang, ran, counter){
let languages = this.state.languages;
languages[counter]=lang;
this.setState({
languages: languages,
});
}
render() {
let counter = 0;
return (
<View style={{flex: 1, justifyContent: 'center', backgroundColor: '#fff'}}>
<View style={{flexDirection: 'row', justifyContent: 'center'}}>
<Text style={{
fontSize: 20,
fontFamily: 'normal',
color: 'skyblue',
}}>
{strings('login.whichlanguages')} {'\n'}
</Text>
</View>
{this.state.pickers.map((picker) => {
counter++;
console.log("p"+picker.toString());
return <View key={Math.random()} style={{flexDirection: 'row', justifyContent: 'center'}}>
<Picker style={{width: 150}} selectedValue={this.state.languages[counter-1]}
onValueChange={(lang) => this.update(lang, 0, counter-1)}
>
{
Object.keys(isoLangs).map((lang) => {
return <Picker.Item color="skyblue" key={Math.random()} label={isoLangs[lang].name} value={lang}/>
})
}
</Picker>
<Image
source={require('./assets/Arrow.png')}
/>
<Picker style={{width: 150}} selectedValue={this.state.languages2[counter-1]}
onValueChange={(lang) => this.update2(lang, 0, counter-1)}
>
{
Object.keys(isoLangs).map((lang) => {
return <Picker.Item color="skyblue" key={Math.random()} label={isoLangs[lang].name} value={lang}/>
})
}
</Picker>
</View>
})}
<View style={{flexDirection: 'row', justifyContent: 'center'}}>
<TouchableHighlight onPress={() => this.addLanguage()}>
<Text style={{
fontSize: 25,
fontFamily: 'normal',
alignItems: 'center',
color: 'skyblue',
}}>{'\n'}+ {strings('login.addlanguage')}{'\n'}{'\n'}</Text>
</TouchableHighlight>
</View>
<View style={{flexDirection: 'row', justifyContent: 'center'}}>
<TouchableHighlight onPress={() => this.props.navigation.navigate('Screen3')}>
<Image
source={require('./assets/Next.png')}
/>
</TouchableHighlight>
</View>
</View>
);
}
}
const adresses = [
{
street: "English",
city: "Sydney",
country: "Australia"
},{
street: "Estonian",
city: "Sydney",
country: "Australia"
},{
street: "Esperanto",
city: "Sydney",
country: "Australia"
}
];
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
class AutoComplete extends React.Component {
constructor(props) {
super(props);
this.state = {
searchedAdresses: []
};
}
submit() {
}
searchedAdresses = (searchedText) => {
let searchedAdresses = adresses.filter(function(adress) {
return adress.street.toLowerCase().indexOf(searchedText.toLowerCase()) > -1;
});
this.setState({searchedAdresses: searchedAdresses});
};
renderAdress = (adress) => {
return (
<TouchableHighlight onPress={() => this.submit()}>
<View>
<Text>{adress.street}</Text>
</View>
</TouchableHighlight>
);
};
render() {
return (
<View style={styles.row}>
<View style={styles.container2}>
<TextInput
style={styles.textinput}
onChangeText={this.searchedAdresses}
placeholder="Type your language here" />
<ListView
dataSource={ds.cloneWithRows(this.state.searchedAdresses)}
renderRow={this.renderAdress} />
</View>
<View style={styles.container2}>
<TextInput
style={styles.textinput}
onChangeText={this.searchedAdresses}
placeholder="Type your language here" />
<ListView
dataSource={ds.cloneWithRows(this.state.searchedAdresses)}
renderRow={this.renderAdress} />
</View>
</View>
);
}
}
const RootStack = StackNavigator(
{
Home: {
screen: HomeScreen,
},
Details: {
screen: DetailsScreen,
},
AutoComplete: {
screen: AutoComplete,
},
},
{
initialRouteName: 'Home',
}
);
export default class App extends React.Component {
render() {
return <RootStack/>;
}
}
const styles = StyleSheet.create({
row: {
flex: 1,
flexDirection: "row"
},
container2: {
flex: 0.5,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#FFFFFF',
},
textinput: {
marginTop: 30,
backgroundColor: '#DDDDDD',
height: 40,
width: 150
},
container: {
flex: 1,
paddingTop: Constants.statusBarHeight,
backgroundColor: '#fff',
},
section1: {
flex: 0.17,
justifyContent: 'flex-end',
alignItems: 'center'
},
section2: {
flex: 0.30,
justifyContent: 'flex-start',
alignItems: 'center'
},
section3: {
flex: 0.10,
justifyContent: 'center',
alignItems: 'center'
},
section4: {
flex: 0.43
},
text: {
fontSize: 24,
color: '#53a6db',
textAlign: 'center',
paddingTop: 40,
paddingBottom: 40,
paddingLeft: 40,
paddingRight: 40
},
buttonContainer: {
flex: 1,
flexDirection: 'row'
},
button: {
flex: 0.5,
justifyContent: 'center',
alignItems: 'center'
},
buttonText: {
fontSize: 24,
color: '#53a6db',
textAlign: 'center',
paddingTop: 5,
paddingBottom: 5,
paddingLeft: 5,
paddingRight: 5
},
image: {
width: 100,
height: 100
}
});
Comments can't be used in JSON
You have syntax errors in your .json files by using a comment. Fixed snack.