pass props to DrawerContent component - javascript

I want to pass props to Drawer so that i can display the name of user in the drawer component. If i export DrawerContent, i dont get the props like navigation etc.
routes.js
const navitems =[
{
name:'Home',
nav:'classesnew',
},
{
name:'Device',
nav:'start',
},
]
const mapDispatchToProps = (dispatch) => (
{
loadInitialData: () => dispatch(loadInitialData()),
}
);
const mapStateToProps = createStructuredSelector({
user: selectUser(), // fetch the name of user to show below
});
class DrawerContent extends React.Component{
constructor(props) {
super(props)
}
render(){
return (
<Image source={require('../images/logo.png')}
style={styles.container}>
<View style={{justifyContent: 'center',
alignItems: 'center',}}>
<Image style={styles.image} source={{uri: ''}}/>
<Text>{user.get('name')}</Text> {/* show username */}
</View>
<View>
{
navitems.map((l,i)=>{
return (
<TouchableOpacity
key={i}
style={{marginBottom:0.5}}
onPress={()=>{
this.props.navigation.navigate(l.nav)
}
}>
<View style={{flexDirection:'row', padding: 15, paddingLeft:0, backgroundColor:'#fff0', borderTopWidth:0.5, borderColor:'rgba(255,255,255, 0.5)', marginLeft: 20, marginRight:20}}>
<Icon name={l.icon} size={20} style={{paddingLeft:10, paddingRight: 20, height: 25, }} color="#ffffff" />
<Text style={{fontSize:16, fontWeight: 'bold',color:'#fff'}}>{l.name}</Text>
</View>
</TouchableOpacity>)
})
}
</View>
</Image>)
}
}
const DrawerRoutes = (
{
Main: { screen: App, title: 'Main' },
Device: { screen: Device, title: 'Device' },
})
const Drawer = DrawerNavigator(DrawerRoutes ,{
contentComponent:({navigation})=> <DrawerContent navigation={navigation} routes={DrawerRoutes} />,
});
Drawer.navigationOptions = {
contentOptions: {
activeBackgroundColor: '#ff5976',
style: {
backgroundColor: '#000000',
zIndex: 100,
paddingTop: 0
}
},
header: ({ state, setParams, navigate, dispatch }) => ({
visible: true,
tintColor: '#ffffff',
title: "LokaLocal",
style: {
backgroundColor: '#ff5976'
},
right: (
<TouchableOpacity
onPress={() => navigate('DrawerOpen')}
>
<Icon name="search" size={16} style={{ padding: 10, paddingRight: 20 }} color="#ffffff" />
</TouchableOpacity>
),
left: (
<TouchableOpacity
onPress={}
>
<Icon name="bars" size={16} style={{ padding: 10, paddingLeft: 20 }} color="#ffffff" />
</TouchableOpacity>
),
})
}
export const Routes = StackNavigator(
{
Login: { screen: Login },
Dashboard: {screen: Drawer},
},
index.js
import { Drawer } from './routes';
const App = () => (
<Provider store={store}>
<Drawer />
</Provider>
);
where should i use connect so i can use redux state as props to show username?
UPDATED
const mapDispatchToProps = (dispatch) => (
{
loadInitialData: () => dispatch(loadInitialData()),
}
);
const mapStateToProps = createStructuredSelector({
user: selectUser(),
});
class DrawerContent extends React.Component{
constructor(props) {
super(props)
}
componentDidMount() {
console.log('props are', this.props);
this.props.loadInitialData();
}
render() {
console.log('props', this.props);
return (
<View style={styles.container}>
<View>
<Image style={styles.image} source={require('../images/logo.png')}/>
<Text style={{ color: '#fff', fontSize: 11, paddingTop: 10, paddingBottom: 20 }}>username here</Text>
</View>
<View>
{
navitems.map((l,i)=>{
return (
<TouchableOpacity
key={i}
style={{marginBottom:0.5}}
onPress={()=>{
this.props.navigation.navigate(l.nav)
}
}>
<View style={{flexDirection:'row', padding: 15, paddingLeft:0, borderTopWidth:0.5, borderColor:'rgba(255,255,255, 0.5)',}}>
<Icon name={l.icon} size={20} style={{paddingLeft:10, paddingRight: 20, height: 25, }} color="#ffffff" />
<Text style={{fontSize:16, fontWeight: 'bold',color:'#fff'}}>{l.name}</Text>
</View>
</TouchableOpacity>)
})
}
</View>
</View>
)
}
}
const DrawerRoutes = (
{
Main: { screen: App, title: 'Main' },
Device: { screen: Device, title: 'Device' },
})
export const Drawer = DrawerNavigator(DrawerRoutes ,{
contentComponent:({navigation})=> <ContentDrawer navigation={navigation} routes={DrawerRoutes} />,
});
const ContentDrawer = connect(mapStateToProps, mapDispatchToProps)(DrawerContent);

Related

Issue with custom header (scene.route is undefined)

I'm trying to have a custom header component in react native navigation 5, however I'm getting the following error:
TyperError: undefined is not an object (evaluating 'scene.route')
In my component:
export default CustomHeader2 = (props) =>
{
const {scene, previous, navigation } = props;
return (
<View style={{ width:'100%',height:50, flexDirection:'row', alignItems:'center', justifyContent:'space-between', backgroundColor:'white' }}>
<View style={{ height:50, flexDirection:'row', alignItems:'center' }}>
{previous ?
(<TouchableOpacity onPress={ ()=>{ navigation.goBack() } } style={{ width:50, height:'100%',flexDirection:'column',alignItems:'center', justifyContent:'center' }}>
<MaterialCommunityIcon name="arrow-left" style={{ color:'black', marginRight:0, fontSize:30 }}/>
</TouchableOpacity>)
:null
}
<Text style={{ fontSize:18, color:'rgb(68,68,68)',fontWeight:'bold' }}>{ scene.route.params.venue.name }</Text>
</View>
</View>
);
};
In my stack:
<Stack.Screen
name="VenueCard8"
component={VenueCard8}
headerShown={true}
options={({ route }) => ({ title: route.params.venue.name, header: () => (<CustomHeader2></CustomHeader2>) })}
/>
screen options
options={() => ({
header: (props) => (
<CustomHeader
{...props}
/>
)
})}
custom header:
const CustomHeader = (props) => {
console.log('props = ', props);
console.log('scene = ', props.scene);
return (
<View>
<Text>Hello</Text>
</View>
);
};
Try this way
export default CustomHeader2 = (props) => {
return (
.........
<Text style={.....}>{ props.route.params.venue.name }</Text>
......
);
};

React Native: How to dispatch redux action from Custom Drawer

I have to dispatch logoutUser() action from CustomDrawerContentComponent. How can I do that?
I have a StackNavigator as well as Drawer Navigator in my app.
Also there is a CustomDrawerComponent to show the username of authenticated user as well as a sign up button in Drawer. Since it is outside the class, I'm unable to dispatch using props.
MainComponent.js
...other import statements
import {
fetchDishes,
fetchComments,
fetchPromos,
fetchLeaders,
logoutUser,
} from "../redux/ActionCreators";
const mapDispatchToProps = (dispatch) => ({
fetchDishes: () => dispatch(fetchDishes()),
fetchComments: () => dispatch(fetchComments()),
fetchPromos: () => dispatch(fetchPromos()),
fetchLeaders: () => dispatch(fetchLeaders()),
logoutUser: () => dispatch(logoutUser()),
});
const handleSignOut = () => {
//Here I have to dispatch logoutUser() but props.logoutUser() says undefined.
};
const CustomDrawerContentComponent = (props) => (
<ScrollView>
<SafeAreaView
style={styles.container}
forceInset={{ top: "always", horizontal: "never" }}
>
<View style={styles.drawerHeader}>
<View style={{ flex: 1 }}>
<Image
source={require("./images/newlogo.png")}
style={styles.drawerImage}
/>
</View>
<View style={{ flex: 2 }}>
<Text style={styles.drawerHeaderText}>Ristorante Con Fusion</Text>
</View>
</View>
<View style={styles.displayName}>
<Avatar
title={props.screenProps.name.match(/\b(\w)/g).join("")}
rounded
>
{" "}
</Avatar>
<Text style={{ fontSize: 22, marginLeft: 5, color: "#fff" }}>
Hello, {props.screenProps.name}
</Text>
</View>
<DrawerItems {...props} />
<TouchableOpacity onPress={() => handleSignOut()}> //Here I am calling the function
<View style={{ flexDirection: "row", justifyContent: "center" }}>
<Icon name="sign-out" type="font-awesome" size={24} color="blue" />
<Text>Sign Out</Text>
</View>
</TouchableOpacity>
</SafeAreaView>
</ScrollView>
);
const MainNavigator = createDrawerNavigator(
{
Home: {
screen: HomeNavigator,
navigationOptions: {
title: "Home",
drawerLabel: "Home",
drawerIcon: ({ tintColor, focused }) => (
<Icon name="home" type="font-awesome" size={24} color={tintColor} />
),
},
},
...
...
...
{
initialRouteName: "Home",
drawerBackgroundColor: "#D1C4E9",
contentComponent: CustomDrawerContentComponent,
}
);
class Main extends Component {
componentDidMount() {
this.props.fetchDishes();
this.props.fetchComments();
this.props.fetchPromos();
this.props.fetchLeaders();
};
render() {
var displayName = this.props.user.user.displayName;
if (displayName == undefined) displayName = this.props.user.name;
return (
<Fragment>
<View
style={{
flex: 1,
paddingTop:
Platform.OS === "ios" ? 0 : Expo.Constants.statusBarHeight,
}}
>
<MainNavigator screenProps={{ name: displayName }} />
</View>
</Fragment>
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Main);
You can use the following to import useDispatch
import { useDispatch } from 'react-redux'
and then call it in your handleSignOut like so:
const handleSignOut = () => {
const dispatch = useDispatch()
dispatch(logoutUser())
//Continue with normal logout and maybe other dispatches...
};
Your component is not connected to redux. You are not using mapDispatchToProps anywhere else besides declaring it. Please use connect() method https://react-redux.js.org/api/connect

TypeError:undefined is not an object evaluating this.state.items

I'm new to React native and development in general and am trying to retrieve data from an webservice and then render it but I seem to be running into different errors.
I am getting this error
import React, { Component } from "react";
import {StyleSheet,View,ActivityIndicator,FlatList,Text,TouchableOpacity} from "react-native";
export default class Source extends React.Component {
static navigationOptions = ({ navigation }) => {
return {
title: "Source Listing",
headerStyle: {backgroundColor: "#fff"},
headerTitleStyle: {textAlign: "center",flex: 1}
};
};
constructor(props) {
super(props);
this.state = {
loading: false,
items:[]
};
this.fetchRequest=this.fetchRequest.bind.this
}
FlatListItemSeparator = () => {
return (
<View style={{
height: .5,
width:"100%",
backgroundColor:"rgba(0,0,0,0.5)",
}}
/>
);
}
componentDidMount()
{
fetchRequest();
}
renderItem=(data)=>
<TouchableOpacity style={styles.list}>
<Text style={styles.lightText}>{data.item.name}</Text>
<Text style={styles.lightText}>{data.item.email}</Text>
<Text style={styles.lightText}>{data.item.company.name}</Text>
</TouchableOpacity>
render(){
fetchRequest()
{
const parseString = require('react-native-xml2js').parseString;
fetch('http://192.168.200.133/apptak_service/apptak.asmx/Get_Item_Master')
.then(response => response.text())
.then((response) => {
parseString(response, function (err, result) {
console.log(response)
});
}).catch((err) => {
console.log('fetch', err)
this.fetchdata();
})
if(this.state.loading){
return(
<View style={styles.loader}>
<ActivityIndicator size="large" color="#0c9"/>
</View>
)}}
return(
<View style={styles.container}>
<FlatList
data= {this.state.dataSource}
ItemSeparatorComponent = {this.FlatListItemSeparator}
renderItem= {item=> this.renderItem(item)}
keyExtractor= {item=>item.id.toString()}
/>
</View>
)}
}
<FlatList
data={this.state.items}
renderItem={({ item }) => <Item title={item.title} />}
keyExtractor= {item=>item.id.toString()}
/>
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff"
},
loader:{
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#fff"
},
list:{
paddingVertical: 4,
margin: 5,
backgroundColor: "#fff"
}
});
The main cause what i am trying to achieve is render the 'items' that are returned from the webservice.
Kindly guide me with this error

How to render a partial view on another view in react native

When I tried alert("Hi") in renderMoreView function, it actually works, but to display the View is the problem I am facing
export default class Home extends Component {
state = {
moreButton: false,
};
renderMoreView = () => {
return (
<View style={{flex: 1, height: 50, width: 50}}>
<Text>Hi</Text>
</View>
);
};
render () {
return (
<View>
.....
<TouchableOpacity
underlayColor="transparent"
onPress={() => this.setState ({moreButton: true})}
>
<Feather name="more-vertical" size={25} />
</TouchableOpacity>
...
{this.state.moreButton ? this.renderMoreView () : null}
</View>
);
}
}
This is what I am trying to do]
If I understand your question right, you could use Modal component. https://facebook.github.io/react-native/docs/modal
This can be done using modal. But if you want to do it more simply, install and use the module. react-native-awesome-alerts
$ npm i react-native-awesome-alerts --save
Example
import React from 'react';
import { StyleSheet, View, Text, TouchableOpacity } from 'react-native';
import AwesomeAlert from 'react-native-awesome-alerts';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = { showAlert: false };
};
showAlert = () => {
this.setState({
showAlert: true
});
};
hideAlert = () => {
this.setState({
showAlert: false
});
};
render() {
const {showAlert} = this.state;
return (
<View style={styles.container}>
<Text>I'm AwesomeAlert</Text>
<TouchableOpacity onPress={() => {
this.showAlert();
}}>
<View style={styles.button}>
<Text style={styles.text}>Try me!</Text>
</View>
</TouchableOpacity>
<AwesomeAlert
show={showAlert}
showProgress={false}
title="AwesomeAlert"
message="I have a message for you!"
closeOnTouchOutside={true}
closeOnHardwareBackPress={false}
showCancelButton={true}
showConfirmButton={true}
cancelText="No, cancel"
confirmText="Yes, delete it"
confirmButtonColor="#DD6B55"
onCancelPressed={() => {
this.hideAlert();
}}
onConfirmPressed={() => {
this.hideAlert();
}}
/>
</View>
);
};
};
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#fff',
},
button: {
margin: 10,
paddingHorizontal: 10,
paddingVertical: 7,
borderRadius: 5,
backgroundColor: "#AEDEF4",
},
text: {
color: '#fff',
fontSize: 15
}
});

JSX attributes must only be assigned a non-empty expression

I am trying to create a custom drawer in react-navigation. However I am getting an error. The error is JSX attributes must only be assigned a non-empty expression. I have even create the array and maped it to show but still getting an error. Did i miss anything?
import { StackNavigator, DrawerNavigator } from 'react-navigation';
import { View, Text, Image, TouchableOpacity } from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
const navitems =[
{
name:'Home',
nav:'classesnew',
},
{
name:'Device',
nav:'start',
},
]
class DrawerContent extends React.Component{
constructor(props) {
super(props)
}
render(){
return (
<Image source={require('../images/logo.png')}
style={styles.container}>
<View style={{justifyContent: 'center',
alignItems: 'center',}}>
<Image style={styles.image} source={{uri: ''}}/>
</View>
<View>
{
navitems.map((l,i)=>{
return (
<TouchableOpacity
key={i}
style={{marginBottom:0.5}}
onPress={()=>{
this.props.navigation.navigate(l.nav)
}
}>
<View style={{flexDirection:'row', padding: 15, paddingLeft:0, backgroundColor:'#fff0', borderTopWidth:0.5, borderColor:'rgba(255,255,255, 0.5)', marginLeft: 20, marginRight:20}}>
<Icon name={l.icon} size={20} style={{paddingLeft:10, paddingRight: 20, height: 25, }} color="#ffffff" />
<Text style={{fontSize:16, fontWeight: 'bold',color:'#fff'}}>{l.name}</Text>
</View>
</TouchableOpacity>)
})
}
</View>
</Image>)
}
}
const DrawerRoutes = (
{
Main: { screen: App, title: 'Main' },
Device: { screen: Device, title: 'Device' },
})
const Drawer = DrawerNavigator(DrawerRoutes ,{
contentComponent:({navigation})=> <DrawerContent navigation={navigation} routes={DrawerRoutes} />,
});
Drawer.navigationOptions = {
contentOptions: {
activeBackgroundColor: '#ff5976',
style: {
backgroundColor: '#000000',
zIndex: 100,
paddingTop: 0
}
},
header: ({ state, setParams, navigate, dispatch }) => ({
visible: true,
tintColor: '#ffffff',
title: "LokaLocal",
style: {
backgroundColor: '#ff5976'
},
right: (
<TouchableOpacity
onPress={() => navigate('DrawerOpen')}
>
<Icon name="search" size={16} style={{ padding: 10, paddingRight: 20 }} color="#ffffff" />
</TouchableOpacity>
),
left: (
<TouchableOpacity
onPress={}
>
<Icon name="bars" size={16} style={{ padding: 10, paddingLeft: 20 }} color="#ffffff" />
</TouchableOpacity>
),
})
}
export const Routes = StackNavigator(
{
Login: { screen: Login },
Dashboard: {screen: Drawer},
},
);
I am using react-navigation 1.0.0.bet.9
<TouchableOpacity
onPress={}
Here , as the error mentioned , you can't assign an empy expression to a JSX attributes.
You can't have empty {} in JSX attributes.
In here you can't have
<TouchableOpacity
onPress={}
>
Fix this by having
<TouchableOpacity
onPress={someFunction}
>
Error:
onPress={}
You have to pass a prop but to run this temporary you can do this as :
onPress={""}
let me know if it worked :)

Categories

Resources