How to access the react-navgiation inside of a functional component or class component which doesnt have access to this.props.navigation? - react-native

Im doing this inside the react native platform using expo.
I want to display the list of items ( ListItems.js) All_Employees_screen.js . These items are being rendered via a functional component, I want to have a onRowPress() handler to so that upon clicking it i can navigate it to another view, but I dont know how to do it on react-navigation ?
Or since the new functional component can be a class component( this would be better ) how can i access the navigation thing inside it ?
AllProperties.js
import _ from 'lodash';
import React, {
Component
} from 'react';
import {
Button,
ListView,
ScrollView
} from 'react-native';
import ListItem from './ListItem';
import { connect } from 'react-redux';
import { propertiesFetch } from '../../actions';
// import { FormLabel, FormInput } from 'react-native-elements'
class AllPropertiesScreen extends React.Component {
componentWillMount(){
this.props.propertiesFetch();
this.createDataSource(this.props);
}
// we do this componentWillMount & componentWillReceiveProps (nextProps) thing twice, coz once the component is
// loaded it loads all teh values but when user hits another view like Create property, The Property data still exists
// in the global state object,
// we could move all the dc dataSource code into componentWillReceiveProps but its actually gonna benefit us
// if we make sure that we try to build our data source both when the component first loads up
// & when second time after we go back and forth other compoennts.
componentWillReceiveProps(nextProps){
// nextProps are the next set of props that this component will be rendered with
// this.props is still the old set of props
this.createDataSource(nextProps);
}
createDataSource({ properties }){
const ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2
});
this.dataSource = ds.cloneWithRows(properties);
}
static navigationOptions = ({ navigation }) => {
const {state, setParams} = navigation;
return {
title: 'All Emplooyee',
headerRight: (
<Button
title='Add'
// onPress={() => setParams({ mode: isInfo ? 'none' : 'info'})}
onPress={() => navigation.navigate('createProperty')
}
/>
),
};
};
goBack(){
console.log('65 - go Back clicked');
}
renderRow(property){
// console.log('67-AllPropertiesScreen =', property);
return <ListItem property={property}
onPress={() => { console.log('65 - go Back clicked') }}
/>;
}
render() {
console.log('72-AllPropertiesScreen this.props', this.props );
return(
<ListView
enableEmptySections
dataSource={this.dataSource}
renderRow={this.renderRow}
/>
);
}
}
const mapStateToProps = state => {
console.log('83 - AllPropertiesScreen state. properties', state );
const properties = _.map(state.properties, (val, uid ) => {
return { ...val, uid }; // { shift: 'Monday'}
});
return { properties };
};
export default connect(mapStateToProps, {propertiesFetch}) (AllPropertiesScreen);
ListItem.js
import React, { Component } from 'react';
import { Text, TouchableWithoutFeedback, View } from 'react-native';
class ListItem extends Component {
// onRowPress(){
// Actions.employeeEdit({ employee: this.props.employee });
// }
render(){
const { agent_name, cell, address } = this.props.property;
console.log('14- ListItem ', this.props);
return (
<View>
<CardSection>
<Text style={styles.titleStyle}>
name
</Text>
<Text style={styles.titleStyle}>
cell
</Text>
<Text style={styles.titleStyle}>
address
</Text>
</CardSection>
</View>
);
}
}
const styles = {
titleStyle: {
fontSize: 18,
paddingLeft: 15
}
}
export default ListItem;
//
main.js ( this is where I have all the navigation paths hookedup.
class App extends React.Component {
render() {
const MainNavigator = TabNavigator({
// auth: { screen : AuthScreen },
// review: { screen: ReviewScreen },
// signup: { screen : SignupScreen },
followup: { screen: FollowupScreen }, welcome: { screen : WelcomeScreen },
auth: { screen : AuthScreen },
signup: { screen : SignupScreen },
main: {
screen: TabNavigator ({
followup: { screen: FollowupScreen },
map: { screen: MapScreen },
deck: { screen: DeckScreen },
settings : {
screen: StackNavigator ({
settings: { screen: SettingsScreen },
// settings: { screen: SettingsScreen },
UserProfile: { screen: UserProfileScreen },
HelpSupport: { screen: HelpSupportScreen },
Notifications: { screen: NotificationsScreen },
Signout: { screen: SignoutScreen } // not working, Navigation object not accessible inside the component
}) //screen: StackNavigator ({
},
followup : {
screen: StackNavigator ({
followup: { screen: FollowupScreen },
allProperties: { screen: AllPropertiesScreen },
createProperty: { screen: PropertyCreateScreen },
Red: { screen: RedPriorityScreen }, // not working, Navigation object not accessible inside the component
GreyPriority: { screen: GreyPriorityScreen },
}) //screen: StackNavigator ({
},
draw: {
screen: DrawerNavigator ({
drawin: { screen: DrawScreen },
}) //screen: StackNavigator ({
}
}) //screen: TabNavigator
}
}, {
navigationOptions: {
tabBarVisible: false
},
lazy: true
});
return (
<Provider store={store}>
<View style={styles.container}>
<MainNavigator />
</View>
</Provider>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
// alignItems: 'center',
justifyContent: 'center',
},
});
Expo.registerRootComponent(App);
Solution suggested by #Matt but as soon as I put the navigation={this.props.navigation} it complains. undefined is not an object ( evaluating this.props.navigation )
renderRow(property){
return (
<ListItem
property={property}
navigation={this.props.navigation}
onPress={() => {
console.log( '70-on Press inside renderRow ');
}}/>
);
}

If the component is not a screen you have to import the navigation.
Try this:
import React from 'react';
import { Button } 'react-native';
import { withNavigation } from 'react-navigation';
class MyBackButton extends React.Component {
render() {
return <Button title="Back" onPress={() => { this.props.navigation.goBack() }} />;
}
}
// withNavigation returns a component that wraps MyBackButton and passes in the
// navigation prop
export default withNavigation(MyBackButton);
For more info check out
https://reactnavigation.org/docs/connecting-navigation-prop.html

This answer was written for old version of react-navigation V1
I had the same exact problem, and I found out that this.props.navigation is injected only in components that are registered as screen in StackNavigator or TabbNavigator.
but in general you can use navigate from NavigationActions class (source here https://v1.reactnavigation.org/docs/navigation-actions.html#navigate)
note: NavigationActions.navigate receives parameters in different way but works the same way.
so this working for me
import { NavigationActions } from 'react-navigation';
let {navigate} = NavigationActions;
renderRow(property) {
return (
<ListItem
property={property}
onPress={() => { navigate({
routeName: 'OtherRoute'
});
}}/>
);
}

<MyComponent navigation={this.props.navigation}/>
Main problem is here. You didn't define your prop navigation in component. You should add this.

Here's how you can use navigation.navigate inside a functional component:
import { Text, TouchableHighlight } from 'react-native';
const MyComponent = ({ navigation }) => (
<TouchableHighlight
onPress={() => navigation.navigate('OtherRoute')}
underlayColor="blue"/>
<Text>Click to Navigate!</Text>
</TouchableHighlight>
);
export default MyComponent;
When you render MyComponent, you will need to pass navigation as a prop. For example, assume HomeContainer is a screen component:
import React from 'react';
import MyComponent from './MyComponent';
export default HomeContainer extends React.Component {
render() {
return (
<MyComponent navigation={this.props.navigation}/>
);
}
}

Change your renderRow method to the following:
renderRow(property) {
return (
<ListItem
property={property}
onPress={() => { this.props.navigation.navigate('OtherRoute'); }}/>
);
}
where 'OtherRoute' is the name of the route you want to navigate to for that row.

Related

'TypeError: Cannot read property 'state' of undefined' error' in react-native

I have created the header using defaultNavigationOptions The navigation bar contains Home, signup, login, create blog options. If the user has signed in then Login option should not be visible, instead, logout option should be enabled. I'm using AsyncStorage to store the token.
App.js:
import React from 'react';
import { CreateBlog } from './app/views/CreateBlog.js';
import { BlogDetails } from './app/views/BlogDetails.js';
import { EditBlog } from './app/views/EditBlog.js';
import { DeleteBlog } from './app/views/DeleteBlog.js';
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import { Home } from './app/views/Home.js';
import { Login } from './app/views/Login.js';
import {
StyleSheet, Text, View, TextInput, TouchableHighlight, Alert, AsyncStorage
} from 'react-native';
import { Signup } from './app/views/Signup.js';
const AppNavigator = createStackNavigator(
{
CreateBlogRT: {
screen: CreateBlog
},
BlogDetailsRT: {
screen: BlogDetails
},
EditBlogRT: {
screen: EditBlog
},
DeleteBlogRT: {
screen: DeleteBlog
},
SignupRT: {
screen: Signup
},
LoginRT: {
screen: Login
},
HomeRT: {
screen: Home,
},
},
{
initialRouteName: 'HomeRT',
defaultNavigationOptions: ({ navigation }) => ({
header: <View style={{
flexDirection: "row",
height: 80,
backgroundColor: '#f4511e', fontWeight: 'bold'
}} >
<TouchableHighlight onPress={() => navigation.navigate('SignupRT')}>
<Text > SignUp</Text>
</TouchableHighlight>
<TouchableHighlight onPress={() => navigation.navigate('CreateChapterRT')}>
<Text > CreateChapter</Text>
</TouchableHighlight>
<TouchableHighlight onPress={() => navigation.navigate('LoginRT')}>
<Text > Login</Text>
</TouchableHighlight>
//getting 'TypeError: Cannot read property 'state' of undefined'
{this.state.logged_in &&
<TouchableHighlight onPress={async () => {
await AsyncStorage.removeItem('token');
await AsyncStorage.removeItem('user_id');
}}>
<Text > Logout</Text>
</TouchableHighlight>
}
</View >
}),
},
}
);
const MyRoutes = createAppContainer(AppNavigator);
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = { logged_in: false };
}
componentDidMount = async () => {
var logged_in = await AsyncStorage.getItem('token')
this.setState({ logged_in: false })
}
render() {
return (
<MyRoutes />
);
}
}
Now on clicking the logout button, it deletes the token. I want the logout button should be visible only if the user has logged in. In the same way login & signup options as well. (
const loggedin=AsyncStorage.getItem('token');if(userloggedin)
{showlogout:true;showlogin:false;showSignup:false}.
I don't know where to write the code. Thanks in advance.
after sign-in user you can set userloggedin true
AsyncStorage.setItem('userloggedin',JSON.stringfy(true)
or
AsyncStorage.setItem('userloggedin',Boolean(true))
then getItem
const logged-in = AsyncStorage.getItem('userloggedin')
if(loggedin){
showlogout=true
showlogin=false
showSignup=false
or if your are using state
this.setState({
showlogout:true,
showlogin:false,
showSignup:false})
}.
you can use react life-cycle for this work and also use global variable or state , like this
check this image
https://camo.githubusercontent.com/3beddc08b0e4b44fbdcef20809484f9044e091a2/68747470733a2f2f63646e2d696d616765732d312e6d656469756d2e636f6d2f6d61782f323430302f312a736e2d66746f7770305f565652626555414645434d412e706e67
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {logged_in: false};
}
componentDidMount=async() {
var logged_in = await AsyncStorage.getItem('token')
this.setState({logged_in: false})
}
render() {
const {logged_in} = this.state
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {logged_in}.</h2>
</div>
);
}
}

this.props.navigation.toggedrawer is not a function-React Native 0.59.9 React Navigation 3.11.0

I have a requirement of using Redux in Tabnavigator which is inside of
an DrawerNavigator.Redux Portion is working fine, But I am unable to
open the drawer on click of a button but the drawer is visible on
swipe gesture.
I am providing my code:-
App.js:-
import * as React from 'react';
import {createAppContainer,createStackNavigator,createBottomTabNavigator} from 'react-navigation';
import RegisterStack from './routes/Register.route';
import SplashStack from './routes/Splash.route';
import Test from './src/pages/Test';
const AppNavigator = createStackNavigator(
{
Splash: SplashStack,
Register: RegisterStack,
StartTest :Test
},
{
initialRouteName: 'StartTest',
headerMode:'none'
});
let Navigation = createAppContainer(AppNavigator);
export default class App extends React.Component {
render() {
return (
<Navigation />
);
}
}
code in Test.js:-
import React from 'react';
import { View,StyleSheet,Text,SafeAreaView,Dimensions,Button } from 'react-native';
import {createAppContainer,createMaterialTopTabNavigator,createDrawerNavigator, DrawerActions} from 'react-navigation';
import ReferenceStack from './Reference';
import QuestionStack from './Question';
import { Provider, connect } from 'react-redux';
import { createStore, combineReducers } from 'redux';
function counter(state, action) {
if (typeof state === 'undefined') {
return 0;
}
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
}
let store = createStore(combineReducers({ count: counter }));
class DrawerLayout extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<SafeAreaView style={styles.container}>
<Text>{this.props.count}</Text>
<Button
title="Increment"
onPress={() => this.props.dispatch({ type: 'INCREMENT' })}
/>
</SafeAreaView>
)
}
}
const styles = StyleSheet.create({
container: {
flex:1,
backgroundColor: "red",
}
});
let CounterContainer = connect(state => ({ count: state.count }))(ReferenceStack);
let StaticCounterContainer = connect(state => ({ count: state.count }))(QuestionStack);
let StaticCounterContainerDrawer = connect(state => ({ count: state.count }))(DrawerLayout);
const DrawerStack = createDrawerNavigator({
Test: {
screen: createMaterialTopTabNavigator({
Reference: {
screen: CounterContainer
},
Question:{
screen: StaticCounterContainer
}
},{
tabBarPosition: 'bottom',
tabBarOptions:{
activeTintColor:'#d61822',
inactiveTintColor:'#5e5e5e',
pressColor:'#d61822'
}
})
}
},{
drawerPosition: "left",
drawerWidth: Dimensions.get('screen').width*.80,
contentComponent: StaticCounterContainerDrawer
});
let DrawerTabNavigation = createAppContainer(DrawerStack);
class Test extends React.Component {
constructor(props) {
super(props);
console.log(props)
}
render() {
return (
<View style={{flex:1}}>
<View style={{height:50,backgroundColor:'yellow'}}></View>
<Provider store={store}>
<DrawerTabNavigation/>
</Provider>
<View style={{height:50,backgroundColor:'yellow'}}>
<Button
title="Open Drawer"
onPress={() => this.props.navigation.toggleDrawer()}
/>
</View>
</View>
);
}
}
export default Test;
When ever Open Drawer button is pressed
_this3.props.navigation.toggedrawer is not a function this error is showing.
I am providing the screen and the error also:-
Please hekp me to open the drawer on click of a button. Thanks in
advance
this.props.navigation.toggedrawer will work only for the screens which are in DrawerNavigator.
May be try this.
import { DrawerActions } from "react-navigation";
this.props.navigation.dispatch(DrawerActions.toggleDrawer())

react navigationv2, navigate function not in header props

I have setup my StackNavigator like so:
const AppNavigator = StackNavigator(
{
Home: {
screen: HomeScreen
},
Month: {
screen: Month
},
Day: {
screen: Day
}
},
{
headerMode: "screen",
navigationOptions: {
header: props => <CustomHeader {...props} />
}
}
);
I can navigate from each screen using this.props.navigation.navigate("Month");
However, in my CustomHeader, I cannot see this prop navigate to invoke. I need to navigate back to the home screen using a button in my header.
resetForm() {
const {
resetForm,
clearCredentials,
navigation
} = this.props;
this.props.navigation.navigate("Home");
}
How can I access the navigate prop to move to another screen?
CustomHeader in full:
import React, { Component } from "react";
import { connect } from "react-redux";
import {
Image,
View,
Text,
Modal,
Button,
TouchableOpacity,
AsyncStorage,
StyleSheet,
Platform,
Alert,
TouchableHighlight
} from "react-native";
import Icon from "react-native-vector-icons/MaterialCommunityIcons";
import { NavigationActions } from "react-navigation";
import {
setYear,
setStudent,
setGroup,
fetchCategories,
resetForm,
resetData,
fetchEvents
} from "../actions/events";
class CustomHeader extends Component {
constructor() {
super();
this.resetForm = this.resetForm.bind(this);
this.fetchEvents = this.fetchEvents.bind(this);
this.showAlert = this.showAlert.bind(this);
}
resetForm() {
const navigateAction = NavigationActions.navigate({
routeName: "Home",
params: {},
action: NavigationActions.navigate({ routeName: "Home" })
});
this.props.dispatch(navigateAction);
}
showAlert() {
Alert.alert("Events refreshed");
}
fetchEvents() {
const {
fetchEvents,
navigate,
credentials: { group }
} = this.props;
resetData();
fetchEvents(group);
navigate("Month");
this.showAlert();
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity onPress={this.resetForm}>
<Image
source={require("../img/logout.png")}
style={{ width: 25, height: 30 }}
/>
</TouchableOpacity>
<TouchableOpacity onPress={this.fetchEvents}>
<Image
source={require("../img/refresh.png")}
style={{ width: 20, height: 30 }}
/>
</TouchableOpacity>
</View>
);
}
}
const mapDispatchToProps = dispatch => {
return {
resetForm: () => dispatch(resetForm()),
fetchEvents: id => dispatch(fetchEvents(id)),
resetData: () => dispatch(resetData())
};
};
const mapStateToProps = state => {
return {
categories: state.fetchCategories,
isLoading: state.isLoading,
credentials: state.setCredentials
};
};
export default connect()(CustomHeader);
You must pass navigation to navigationOptions to use in header component. Your AppNavigator should be like this
const AppNavigator = StackNavigator(
{
Home: {
screen: HomeScreen
},
Month: {
screen: Month
},
Day: {
screen: Day
}
},
{
headerMode: "screen",
navigationOptions: ({ navigation }) => ({
header: props => <CustomHeader {...props} navigation={navigation}/>
})
}
);
CustomHeader
...
resetForm() {
const {navigation} = this.props;
navigation.navigate("Home");
}
...

react-native-navigation cant navigate to another page

I searched and compare it to proper solutions nothing look wrong but I almost get the error screen shown below;
Whats wrong with navigation code here;
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TouchableOpacity
} from 'react-native';
import { StackNavigator } from 'react-navigation';
import About from './app/components/About';
export default class Home extends Component {
static navigationOptions = {
title: 'Welcome',
};
navigateToAbout(){
const { navigate } = this.props.navigation;
navigate('About')
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity onPress={()=>this.navigateToAbout()}>
<Text>Go to About Page</Text>
</TouchableOpacity>
</View>
);
}
}
const SimpleApp = StackNavigator({
Home: { screen: Home },
About: { screen: About },
});
AppRegistry.registerComponent('SimpleApp', () => SimpleApp);
I think your code is fine unless you have to bind the method (usually I use an arrow function, but it's ok if you want to bind the method in you constructor), maybe you can try like this way:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TouchableOpacity
} from 'react-native';
import { StackNavigator } from 'react-navigation';
import About from './app/components/About';
export default class Home extends Component {
static navigationOptions = {
title: 'Welcome',
}
navigateToAbout = () => {
this.props.navigation.navigate('About');
}
render() {
const { navigate } = this.props.navigation;
return (
<View style={styles.container}>
<TouchableOpacity onPress={ this._navigateToAbout }
<Text>Go to About Page</Text>
</TouchableOpacity>
</View>
);
}
}
const SimpleApp = StackNavigator({
Home: { screen: Home },
About: { screen: About },
});
AppRegistry.registerComponent('SimpleApp', () => SimpleApp);
I hope it can help you :)
You didn't connect your home component with navigation, you should pass navigation method to the mapDispatchToProps object of connect method.
Here is an example:
import { connect } from 'react-redux'
import { NavigationActions } from 'react-navigation'
const navigate = NavigationActions.navigate
export class Home extends Component {
static navigationOptions = ({ navigation }) => ({
title: 'Welcome',
})
static propTypes = {
navigate: T.func.isRequired,
}
navigateToAbout(){
const { navigate } = this.props.navigation;
navigate({ routeName: 'About' })
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity onPress={()=>this.navigateToAbout()}>
<Text>Go to About Page</Text>
</TouchableOpacity>
</View>
);
}
}
export default connect(null, { navigate })(Home)

React Native React Navigation Header Button Event

Hello I 'm trying to bind a function in my Navigator Right Button,
But It gives error.
This is my code:
import React, { Component } from 'react';
import Icon from 'react-native-vector-icons/FontAwesome';
import Modal from 'react-native-modalbox';
import { StackNavigator } from 'react-navigation';
import {
Text,
View,
Alert,
StyleSheet,
TextInput,
Button,
TouchableHighlight
} from 'react-native';
import NewsTab from './tabs/news-tab';
import CustomTabBar from './tabs/custom-tab-bar';
export default class MainPage extends Component {
constructor(props) {
super(props);
}
alertMe(){
Alert.alert("sss");
}
static navigationOptions = {
title: 'Anasayfa',
headerRight:
(<TouchableHighlight onPress={this.alertMe.bind(this)} >
<Text>asd</Text>
</TouchableHighlight>)
};
render() {
return(
<View>
</View>
);
}
}
And Get error like this:
undefined is not an object (evaluating 'this.alertMe.bind')
When I use this method in render function it is working great but in NavigatonOption I cant get handled it. what can I do for this problem.
You should use this in you navigator function
static navigationOptions = ({ navigation }) => {
const { params = {} } = navigation.state;
return {
title: '[ Admin ]',
headerTitleStyle :{color:'#fff'},
headerStyle: {backgroundColor:'#3c3c3c'},
headerRight: <Icon style={{ marginLeft:15,color:'#fff' }} name={'bars'} size={25} onPress={() => params.handleSave()} />
};
};
use the componentwillmount so that it can represent where you are calling function .
componentDidMount() {
this.props.navigation.setParams({ handleSave: this._saveDetails });
}
and then you can write your logic in the function
_saveDetails() {
**write you logic here for **
}
**no need to bind function if you are using this **
May be same as above ...
class LoginScreen extends React.Component {
static navigationOptions = {
header: ({ state }) => ({
right: <Button title={"Save"} onPress={state.params.showAlert} />
})
};
showAlert() {
Alert.alert('No Internet',
'Check internet connection',
[
{ text: 'OK', onPress: () => console.log('OK Pressed') },
],
{ cancelable: false }
)
}
componentDidMount() {
this.props.navigation.setParams({ showAlert: this.showAlert });
}
render() {
return (
<View />
);
}
}
react-navigation v5 version would be:
export const ClassDetail = ({ navigation }) => {
const handleOnTouchMoreButton = () => {
// ...
};
useLayoutEffect(() => {
navigation.setOptions({
headerRight: () => (
<TouchableOpacity onPress={handleOnTouchMoreButton}>
<Icon name="more" />
</TouchableOpacity>
),
});
}, [navigation]);
return (
// ...
)
}
This is for navigation v4. You need to modify navigationoptions outside of the functional component. Your button event needs to pass a param via navigation.
pageName['navigationOptions'] = props => ({
headerRight: ()=>
<TouchableOpacity onPress={() => props.navigation.navigate("pageRoute",
{"openAddPopover": true}) } ><Text>+</Text></TouchableOpacity> })
and then in your functional component, you can use that param to do something like this:
useLayoutEffect(() => {
doSomethingWithYourNewParamter(navigation.getParam("openAddPopover"))
}, [navigation])