FlatList react native not scrolling - react-native

I have made sure that the parent Views contain flex:1, and I have wrapped the FlatList in a view with Flex 1 but nothing I seem to try enables my flat list to scroll.
I have gone through previous posts and none of the solutions have worked
Any help or suggestions would be greatly appreciated.
This is my code in order from parent to children
const App = () => {
return (
<View style={styles.container}>
<AuthProvider>
<Home />
</AuthProvider>
</View>
);
};
const styles = StyleSheet.create({
container: {flex: 1},
});
export default App;
const Home = () => {
const [userAuth] = useContext(AuthContext);
//{userAuth.auth && <Header title={'Stokebook'} />}
return (
<View style={styles.container}>
{userAuth.auth && <Profile />}
{!userAuth.auth && <LoginHome />}
</View>
);
};
const styles = StyleSheet.create({
container: {flex: 1},
});
const Profile = () => {
const [userAuth] = useContext(AuthContext);
const [Posts, setPosts] = useState();
const [isLoading, setisLoading] = useState(true);
//Loading screen will live here
useEffect(() => {
axios({
method: 'get',
url: 'http://192.168.1.112:3000/posts',
headers: {
Authorization: `${userAuth.token}`,
},
})
.then(response => {
setPosts(response.data.flat());
})
.then(setisLoading(false))
.catch(err => setPosts(err));
}, []);
return (
<View style={styles.PostContainer}>
<FlatList
contentContainerStyle={{height: '100%'}}
data={Posts}
renderItem={({item}) => <Post post={item} />}
/>
</View>
);
};
const styles = StyleSheet.create({
PostContainer: {
backgroundColor: 'grey',
flex: 1,
},
});
const Post = ({post}) => {
return (
<View style={styles.PostContainer}>
<View style={styles.PostHeader}>
<View style={styles.ProfileInfoView}>
<Text>Michael Wong</Text>
<Text>Yesterday at 6.30pm at point leo</Text>
</View>
</View>
<View style={styles.WaveInfo}>
<View>
<Text>Wave height </Text>
<Text> 6ft</Text>
</View>
<View>
<Text>tide </Text>
<Text>low</Text>
</View>
<View>
<Text>Break</Text>
<Text>crunchies</Text>
</View>
<View>
<Text>Wind </Text>
<Text>NE 10km/hr</Text>
</View>
</View>
<View style={styles.ImageView}>
<Image
source={require('../wave.webp')}
style={{flex: 1, width: undefined, height: undefined}}
/>
</View>
<View style={styles.FeedbackView}>
<Text>
<Icon name="thumbs-up" size={15} color="black" /> 13
</Text>
<Text>3 comments</Text>
</View>
<View style={styles.FooterView}>
<View style={styles.IconView}>
<Icon name="thumbs-up" size={30} color="white" />
<Icon name="envelope" size={30} color="white" />
</View>
</View>
</View>
);
};
const styles = StyleSheet.create({
PostContainer: {
backgroundColor: 'beige',
height: '80%',
},
PostHeader: {
height: '20%',
padding: '4%',
flexDirection: 'row',
},
Profileimg: {
height: 30,
width: 30,
borderRadius: 30,
},
ProfileInfoView: {
paddingLeft: '5%',
justifyContent: 'space-around',
},
WaveInfo: {
borderTopWidth: 1,
height: '12%',
flexDirection: 'row',
justifyContent: 'space-evenly',
alignItems: 'center',
},
ImageView: {
height: '60%',
width: '100%',
},
FeedbackView: {
height: '10%',
backgroundColor: 'beige',
flexDirection: 'row',
justifyContent: 'space-between',
padding: '3%',
alignItems: 'center',
},
FooterView: {
width: '100%',
height: '15%',
flexDirection: 'row',
justifyContent: 'center',
backgroundColor: 'black',
borderBottomColor: 'grey',
borderBottomWidth: 12,
},
IconView: {
height: '100%',
width: '70%',
justifyContent: 'space-around',
alignItems: 'center',
flexDirection: 'row',
},
});
export default Post;

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?

i have a problem with passing params to a route in react native navigation. `route.params` is undefined sorry am abit new to react native

Here is my homepage. and i was to navigate to the bookings page while passing a uuid as a param to the bookings page.
import React from "react";
import {
Text,
View,
StatusBar,
ActivityIndicator,
StyleSheet,
SafeAreaView,
TextInput,
TouchableOpacity,
} from "react-native";
import { useFocusEffect } from "#react-navigation/native";
import APIKit from "../config/api/APIKit";
import Icon from "react-native-vector-icons/Feather";
import Card from "../components/Card";
import { ScrollView } from "react-native-gesture-handler";
function HomeScreen({ navigation }) {
const [loading, setLoading] = React.useState(true);
const [items, setItems] = React.useState([]);
const [limit, setLimit] = React.useState(7);
const image = require("../assets/pic1.jpg");
useFocusEffect(
React.useCallback(() => {
getData();
return () => {
setItems([]);
setLimit(9);
};
}, [])
);
const getData = () => {
setLoading(true);
APIKit.get(`items/?limit=${limit}&offset=1`)
.then((res) => {
console.log(res.data);
setLimit(limit + 6);
setItems([items, ...res.data.results]);
setLoading(false);
})
.catch((e) => console.log(e.request.response));
};
return (
<SafeAreaView
style={{ alignItems: "flex-start", justifyContent: "center" }}
>
<StatusBar style="auto" />
<View style={{ padding: 8 }}>
<View
style={{
flexDirection: "row",
alignItems: "center",
width: "100%",
marginTop: 5,
}}
>
<TextInput
placeholder={"Enter Item Name"}
style={{
flex: 1,
backgroundColor: "white",
height: 40,
borderColor: "black",
borderWidth: 1,
borderRadius: 5,
margin: 2,
paddingLeft: 8,
}}
/>
<TouchableOpacity
style={{
alignItems: "center",
alignSelf: "center",
borderWidth: 1,
width: 50,
borderRadius: 500,
}}
>
<Icon name="search" size={25} />
</TouchableOpacity>
</View>
<View style={{ flex: 1, marginTop: 20 }}>
<ScrollView>
<View
style={{
flex: 1,
flexDirection: "row",
flexWrap: "wrap",
justifyContent: "flex-start",
}}
>
{items !== []
? items.map((item, key) => {
return (
<Card
key={key}
name={item.item_name}
description={item.description}
onHandlePress={() =>
navigation.navigate("payment-options", {
uuid: item.uuid,
price: item.cost,
})
}
image={image}
/>
);
})
: null}
</View>
<TouchableOpacity
activeOpacity={0.9}
onPress={getData}
//On Click of button load more data
style={styles.loadMoreBtn}
>
<Text style={styles.btnText}>Load More</Text>
{loading ? (
<ActivityIndicator color="white" style={{ marginLeft: 8 }} />
) : null}
</TouchableOpacity>
</ScrollView>
</View>
</View>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
footer: {
padding: 10,
justifyContent: "center",
alignItems: "center",
flexDirection: "row",
},
loadMoreBtn: {
padding: 10,
width: 350,
marginHorizontal: 20,
alignSelf: "center",
backgroundColor: "#01ab9d",
borderRadius: 4,
flexDirection: "row",
justifyContent: "center",
alignItems: "center",
},
btnText: {
color: "white",
fontSize: 15,
textAlign: "center",
},
});
export default HomeScreen;
and the booking page looks like this
import { Text, View, StatusBar, SafeAreaView, StyleSheet } from "react-native";
import { Button } from "react-native-elements";
import Icon from "react-native-vector-icons/MaterialCommunityIcons";
function PaymentOptionScreen(props) {
return (
<SafeAreaView
style={{ flex: 1, alignItems: "center", justifyContent: "center" }}
>
<StatusBar style="auto" />
<View style={{ flex: 1, justifyContent: "flex-start", margin: 20 }}>
<Button
title="Pay Now"
onPress={() =>
console.log(props.route.params)
}
containerStyle={styles.ButtonContainer}
buttonStyle={{ height: 60, justifyContent: "flex-start" }}
icon={<Icon name="cash" size={40} color="white" />}
/>
<Button
title="Pay on delivery"
containerStyle={styles.ButtonContainer}
buttonStyle={{ height: 60, justifyContent: "flex-start" }}
icon={<Icon name="cash" size={40} color="white" />}
/>
</View>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
ButtonContainer: {
width: 380,
},
});
export default PaymentOptionScreen;
here is a snippet of the of the app.js it may help
<AuthContext.Provider value={authContext}>
<NavigationContainer>
<Drawer.Navigator
initialRouteName="Home"
drawerContent={(props) => <DrawerContent {...props} />}
>
<Drawer.Screen name="Home" component={HomeStackScreen}/>
<Drawer.Screen name="Profile" component={ProfileStackScreen}/>
<Drawer.Screen name="Bookings" component={BookingsStackScreen}/>
<Drawer.Screen name="payment-options" component={PaymentOptionsScreenStack}/>
<Drawer.Screen name="Add Item" component={AddItemStackScreen}/>
<Drawer.Screen name="Settings" component={SettingsStackScreen}/>
<Drawer.Screen name="Messages" component={MessagesStackScreen}/>
</Drawer.Navigator>
</NavigationContainer>
</AuthContext.Provider>
Can you print the props? I think you have to pass it as object {props}
If you are using navigation 5.0 . Try this
const App=({navigation, route })=>{
const uuid = route.param;
return (
<View</View>
);
}

My custom header component goes out of the screen in react native

Problem:
In my react native application I have set up a custom header component like this.
const ChatHeader = (props) => {
return (
<View style={styles.chatHederCiontainer}>
<View style={{flexDirection: 'row'}}>
<View>
<Image
source={require('_assets/img/doctor1.png')}
style={styles.chatImage}
resizeMode="contain"
/>
</View>
<View style={{justifyContent: 'center', marginLeft: 20}}>
{/* {props.name ? (
<View>
<Apptext styles={styles.ChatTextName}>{props.name}</Apptext>
<Apptext styles={styles.ChatTextStatus}>
{props.isActive ? strings('chat.active') : null}
</Apptext>
</View>
) : ( */}
<Apptext styles={styles.ChatText}>
Chat with Doctor and tell your problem
</Apptext>
{/* )} */}
</View>
</View>
</View>
);
};
const mapStateToProps = (state) => {
return {
name: state.feedbacks.chatperson,
isActive: state.feedbacks.active,
};
};
export default connect(mapStateToProps)(ChatHeader);
const styles = StyleSheet.create({
chatHederCiontainer: {
justifyContent: 'center',
alignItems: 'center',
},
chatImageConatiner: {
width: '20%',
},
ChatTextContainer: {
width: '50%',
justifyContent: 'center',
alignItems: 'center',
},
chatImage: {
height: 40,
width: 40,
},
ChatText: {
fontSize: normalize(15),
textAlign: 'center',
alignSelf: 'center',
},
ChatTextName: {
marginLeft: 10,
fontSize: normalize(12),
textAlign: 'center',
},
ChatTextStatus: {
marginLeft: 10,
fontSize: normalize(9),
textAlign: 'left',
},
});
This is how I have used that in my navigations.
<ChatStack.Screen
name="chat"
component={ChatScreen}
options={(props) => ({
headerShown: true,
headerLeft: () => (
<TouchableOpacity
accessibilityRole="tab"
hitSlop={{top: 15, bottom: 15, left: 50, right: 50}}
onPress={() => {
global.currentScreenIndex = 1;
props.navigation.goBack();
}}>
<Icon
name="chevron-left"
size={normalize(15)}
color="#aaaaaa"
style={{marginLeft: 20}}
/>
</TouchableOpacity>
),
headerTitle: () => <HeaderTitle />,
// headerTitleAlign: 'left',
headerStyle: {
backgroundColor: '#f2f2f2',
height: 90,
},
headerTransparent: false,
headerLeftContainerStyle: {},
headerStatusBarHeight: 0,
})}
/>
But when I run in the device it goes out of the device like this.
I tried a lot of things like changing styles but the issue is still the same can someone help me out with this. Thank you very much
Add props headerMode={'none'} to <ChatStack.Screen> tag. Hope help U

Webview Uri Redirect by scanning barcodes with React Native, Expo

I am creating a barcode scanner using React Native and Expo.
I am trying to pass a new URL to a WebView after scanning a barcode.
But I am not sure how.
Please help.
export default function App() {
const [hasPermission, setHasPermission] = useState(null);
const [scanned, setScanned] = useState(false);
const [modalVisible, setModalVisible] = useState(false);
useEffect(() => {
(async () => {
const { status } = await BarCodeScanner.requestPermissionsAsync();
setHasPermission(status === 'granted');
})();
}, []);
const handleBarCodeScanned = ({ type, data }) => {
setScanned(true);
setModalVisible(true);
};
if (hasPermission === null) {
return <Text>Requesting for camera permission</Text>;
}
if (hasPermission === false) {
return <Text>No access to camera</Text>;
}
return (
<View
style={{
flex: 1,
flexDirection: 'column'
}}>
<Modal
animationType="slide"
transparent={false}
visible={modalVisible}
onRequestClose={() => {
setScanned(false);
}}>
<View style={{ flex: 1 }}>
<WebView
style={{ flex: 1 }}
source={{ uri: 'http://domain.biz/' }}
/>
<TouchableHighlight
style={{
backgroundColor:'black',
padding: 15,
alignItems: 'center'
}}
onPress={() => {
setModalVisible(!modalVisible);
setScanned(false);
}}
underlayColor='slategray'
>
<Text style={{ color:'white', fontSize: 15 }}>Re Scan</Text>
</TouchableHighlight>
</View>
</Modal>
<BarCodeScanner
onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
style={{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
}}>
<View style={{ marginBottom: 100 }}>
<View style={{ alignItems: 'center', marginBottom: 5 }}>
<Image
style={{
width: 100,
height: 100,
resizeMode: 'contain',
marginBottom: 20,
}}
source={{ uri: 'http://domain.biz/img/logo_dark.png' }}
/>
<Text style={{ color: 'white', fontSize: 20, fontWeight: 'bold', paddingBottom: 10}}>
QR Code Reader v0.5
</Text>
</View>
<View
style={{
borderColor: 'white',
borderTopWidth: 5,
borderBottomWidth: 5,
borderLeftWidth: 1,
borderRightWidth: 1,
paddingVertical: 80,
paddingHorizontal: 100,
}}
/>
<View style={{ alignItems: 'center', marginTop: 5 }}>
<Text style={{ color: 'white', fontSize: 15}}>
QR Scan...
</Text>
</View>
</View>
</BarCodeScanner>
</View>
);
}
I am creating a barcode scanner using React Native and Expo.
I am trying to pass a new URL to a WebView after scanning a barcode.
But I am not sure how.
Please help.
This should do the work. I save the url from the scanner in state.uri and use that instead of a static string.
For testing purposes I used this barcode which leads to this answer:
Best, Paul
import React, { useState, useEffect } from 'react';
import { Text, View, StyleSheet, Button, Modal, TouchableHighlight, Image } from 'react-native';
import { WebView } from 'react-native-webview';
import { BarCodeScanner } from 'expo-barcode-scanner';
export default function App(){
const [hasPermission, setHasPermission] = useState(null);
const [scanned, setScanned] = useState(true);
const [modalVisible, setModalVisible] = useState(true);
const [uri, setUri] = useState('https://stackoverflow.com/questions/61977154/webview-uri-redirect-by-scanning-barcodes-with-react-native-expo');
useEffect(() => {
(async () => {
const { status } = await BarCodeScanner.requestPermissionsAsync();
setHasPermission(status === 'granted');
})();
}, []);
const handleBarCodeScanned = ({ type, data }) => {
setScanned(true);
setModalVisible(true);
// console.warn("Scan returned " + data);
setUri({ uri: data })
};
if (hasPermission === null) {
return <Text>Requesting for camera permission</Text>;
}
if (hasPermission === false) {
return <Text>No access to camera</Text>;
}
return (
<View
style={{
flex: 1,
flexDirection: 'column'
}}>
<Modal
animationType="slide"
transparent={false}
visible={modalVisible}
onRequestClose={() => {
setScanned(false);
}}>
<View style={{ flex: 1 }}>
<WebView
style={{ flex: 1 }}
source={{uri: uri['uri']}}
/>
<TouchableHighlight
style={{
backgroundColor:'black',
padding: 15,
alignItems: 'center'
}}
onPress={() => {
setModalVisible(!modalVisible);
setScanned(false);
}}
underlayColor='slategray'
>
<Text style={{ color:'white', fontSize: 15 }}>Re Scan</Text>
</TouchableHighlight>
</View>
</Modal>
<BarCodeScanner
onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
style={{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
}}>
<View style={{ marginBottom: 100 }}>
<View style={{ alignItems: 'center', marginBottom: 5 }}>
<Image
style={{
width: 100,
height: 100,
resizeMode: 'contain',
marginBottom: 20,
}}
source={{ uri: 'http://domain.biz/img/logo_dark.png' }}
/>
<Text style={{ color: 'white', fontSize: 20, fontWeight: 'bold', paddingBottom: 10}}>
QR Code Reader v0.5
</Text>
</View>
<View
style={{
borderColor: 'white',
borderTopWidth: 5,
borderBottomWidth: 5,
borderLeftWidth: 1,
borderRightWidth: 1,
paddingVertical: 80,
paddingHorizontal: 100,
}}
/>
<View style={{ alignItems: 'center', marginTop: 5 }}>
<Text style={{ color: 'white', fontSize: 15}}>
QR Scan...
</Text>
</View>
</View>
</BarCodeScanner>
</View>
);
}
Here it is, but I have passed the data from the other page name:index.js.
You can use the linking component to open every URL passed through {data}
import React from "react";
import { View, Text, Linking, TouchableOpacity } from "react-native";
const detail = ({ route, navigation }) => {
const data = route.params;
const [uri, setUri] = React.useState({});
return (
<View>
<TouchableOpacity onPress={() => Linking.openURL(data)}>
<Text>{data}</Text>
</TouchableOpacity>
</View>
);
};
export default detail;

Not able to refer to drawer layout in 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.