I have a custom header for my stack navigation and I want to navigate to another page when I press on an image. But when I press the image I get an error undefined is not an object (evaluating _this.props.navigation.navigate')
In my App.js
const ProfileStackNavi = createStackNavigator({
stackAndTab:{
screen:ProfileTopTabNavigator,
navigationOptions: {
header: (
<MyPageTabBarHeader />
)
},
}
})
In my custom header class
export default class MyPageTabBarHeader extends Component {
constructor(props) {
super(props)
}
render() {
return(
<View style={{width:375,height:250, backgroundColor:'white'}}>
<TouchableOpacity onPress={()=>this.props.navigation.navigate('Register')}>
<Image
style={{width:23, height:23}}
source{require('../Components/Assets/register.png')} />
</TouchableOpacity>
</View>
</View>
)
};
}
I also tried <MyPageTabBarHeader navigation={this.props.navigation}/> but then it gives me the error undefined is not an object (evaluating this.props.navigation.navigate') the same error as previously but without an _ before this.
Edited
In my App.js I have createAppContainer. It looks like this:
const StartSwitchNavigator = createStackNavigator(
{
one:{
screen:screenOne,
},
{
two:{
screen:ProfileStackNavi,
}
);
const App = createAppContainer(StartSwitchNavigator);
export default App;
the navigation isnt being passed properly. try passing it this way :
const ProfileStackNavi = createStackNavigator({
stackAndTab:{
screen:ProfileTopTabNavigator,
navigationOptions: ({navigation}) => ({
header: <MyPageTabBarHeader navigation= {navigation} />,
})
}
})
hope it helps!
It seems the navigation prop isn't being passed down, that's normal for a custom header. The prop is usually only passed to screens/views. You simply have to import withNavigation from 'react-navigation' in your header component and then export default withNavigation(MyPageTabBarHeader) at the bottom of the file instead of when you declare the class.
You will then have access to the navigation prop. Here's some doc about the function.
Related
I have saved one data inside one class of my react-native project. With saving data I start a new screen. In that screen I am retrieving that saved data. For that purpose, I call AsyncStorage.getItem('token') function inside the render function.
Here is the code for that class-
import React from 'react';
import { StyleSheet, Text, View, Image, AsyncStorage } from 'react-native';
import {Icon, Button, Container, Header, Content, Left} from 'native-base';
import CustomHeader from './CustomHeader';
class NoteMeHome extends React.Component {
state = {
text:'',
storedValue:'',
getValue: ''
};
static navigationOptions = ({navigation}) => ({
title: "Home",
headerLeft: <Icon name="ios-menu" style={{paddingLeft:10}}
onPress={()=>navigation.navigate('DrawerOpen')}/>,
drawerIcon:
<Image source={require('../assets/icon.png')}
style={styles.icon}
/>
})
render() {
const {storedValue} = this.state;
AsyncStorage.getItem('token').then(value =>
//AsyncStorage returns a promise so adding a callback to get the value
this.setState({ getValue: value })
//Setting the value in Text
);
return(
<Container>
<CustomHeader
title="Home"
drawerOpen={()=>this.props.navigation.navigate('DrawerOpen')}
/>
<Content contentContainerStyle={{flex:1, alignItems:'center',
justifyContent:'center', padding:10}}>
<Button full onPress={()=> this.props.navigation.navigate('Settings')}>
<Text style={{color:'white'}}>{storedValue}</Text>
</Button>
<Text>{this.state.getValue}</Text>
</Content>
</Container>
)
}
}
const styles = StyleSheet.create({
icon:{
height: 24,
width: 24
}
})
export default NoteMeHome;
After that, while running the project, in the above mentioned class, when I click any of my drawer items to go to another screen, it shows the following error in the console-
wanrning: can't call setState(or forceUpdate) on an unmounted
component. This is no-op, but it indicates a memory leak in your
application. To fix, cancel all subscriptions and asyncshronous tasks
in the componentWillUnmount method.
I guess something goes wrong with AsyncStorage.getItem('token') function calling because if I remove the function it doesn't show any warning.
So, it would be very nice if someone helps me to know where should I call the following code-
AsyncStorage.getItem('token').then(value =>
//AsyncStorage returns a promise so adding a callback to get the value
this.setState({ getValue: value })
//Setting the value in Text
);
to remove the warning ?
Asif,
Here is what I had in mind :
import React from 'react';
import { StyleSheet, Text, View, Image, AsyncStorage } from 'react-native';
import {Icon, Button, Container, Header, Content, Left} from 'native-base';
import CustomHeader from './CustomHeader';
class NoteMeHome extends React.PureComponent {
state = {
text:'',
storedValue:'',
getValue: ''
};
static navigationOptions = ({navigation}) => ({
title: "Home",
headerLeft: <Icon name="ios-menu" style={{paddingLeft:10}}
onPress={()=>navigation.navigate('DrawerOpen')}/>,
drawerIcon:
<Image source={require('../assets/icon.png')}
style={styles.icon}
/>
});
componentDidMount() {
const token = await AsyncStorage.getItem('token');
this.setState({ getValue: token });
}
render() {
const {storedValue, getValue} = this.state;
return(
<Container>
<CustomHeader
title="Home"
drawerOpen={()=>this.props.navigation.navigate('DrawerOpen')}
/>
<Content contentContainerStyle={{flex:1, alignItems:'center',
justifyContent:'center', padding:10}}>
<Button full onPress={()=> this.props.navigation.navigate('Settings')}>
<Text style={{color:'white'}}>{storedValue}</Text>
</Button>
<Text>{getValue}</Text>
</Content>
</Container>
)
}
}
const styles = StyleSheet.create({
icon:{
height: 24,
width: 24
}
})
export default NoteMeHome;
I don't know if in your case you should actually try to handle the update of the component since you don't have any props.
Regards,
IMO you should use componentDidMount for anything that you want to do in the beginning of a screen. To use AsyncStorage remember that is an asynchronous function so you have to wait for the function to complete so you can get the value.
For more information about react native's components please see this
For more information about 'waiting' for AsyncStorage using async please see this examples
In react component render() should always remain pure. One should never set state in render function, it a very bad pracice, in a simple component it might work fine. It only works because of the asynchronicity.
You should use componentDidMount lifecycle method to fetch data from local storage.
componentDidMount() {
const token = await AsyncStorage.getItem('token');
this.setState({ getValue: token });
}
I'm new to ReactNative and started to using TabBarIOS component for a project. I have TabBarIOS component which has 5 different TabBarIOS.Item Component. These each all point another component to present. These different components are all have different backgroundColor's and styles and titles but when I change the selectedTab the change has happened but the properties of components such as backgroundColor not affect the presented component. For testing, I've log a text in componentWillMount method of the Component class for each one. And they logged successfully. Here is the partial components. For the first Component which is named as Restaurants the title is correctly showing in navigationItem but in others navigationItem's title is empty.
I've called my components as ViewControllers.
class RestaurantsComponent extends Component{
componentWillMount(){
console.log('restauranscomponent will mounted');
}
render(){
return(
<View style={{flex:1, backgroundColor:'blue'}}>
<Text>ASDFSADF</Text>
</View>
)
}
}
class SearchViewController extends Component{
componentWillMount(){
console.log('search view controller will mounted');
}
render(){
return(
<View style={{flex:1, backgroundColor:'green'}}>
<Text>askfkjasljkdfjkla</Text>
</View>
)
}
}
etc..
Here is main tabbar Component class:
export default class SimpleClass extends Component{
constructor(props){
super(props);
this.state = {
selectedTab: 'news'
}
}
changeTab(selectedTab){
this.setState({selectedTab})
}
render(){
const { selectedTab } = this.state
const styles = {
backgroundColor: 'red'
};
return(
<TabBarIOS barTintColor="white"
unselectedItemTintColor="gray"
tintColor="red"
style={{flex:1}}
>
<TabBarIOS.Item
selected={selectedTab === 'news'}
title="Restaurants"
icon={require('./assets/restaurants.png')}
onPress={() => this.changeTab('news')}
>
<NavigatorIOS
style={styles.nav}
initialRoute={{
component: RestaurantsComponent,
title : 'Restaurants'
}}
/>
</TabBarIOS.Item>
<TabBarIOS.Item
title="Search"
selected={selectedTab === 'news2'}
onPress={() => this.changeTab('news2')}
icon={require('./assets/searchIco.png')}
>
<NavigatorIOS
style={styles.nav}
initialRoute={{
component: AnotherComponent,
title : 'Search'
}}
/>
</TabBarIOS.Item>
...
.../>
Here is the Component in navigationItem for Restaurants
And for other else:
I'vent cut the tabBar item for the screenshot but the TabBarIOS is successfully works if you mind it.
Is there any bug which is currently which cause from me or what happens to navigationItem's title attributes?
I've found my answer by the way I've not figured out what was happening in here but when looking into documentation and some articles, the use of NavigatorIOS is currently making mess.And there is a cool question & answer that I think its important to get idea of createNavigator... .
Here is the link.
There is a close approach for using TabBar, Navigation etc which are named createStackNavigator and createBottomTabNavigator. As the names tell us, createStackNavigator is currently work like UINavigationController and also createBottomTabNavigator is working like UITabBarController. So this is the basic implementation of these approach.
const firstTabStack = createStackNavigator({
HomeAlways: {
navigationOptions:{
title:'WASSUP1'
},
screen:BooksNav
}
})
const secondTabStack = createStackNavigator({
HelpAlways: {
navigationOptions:{
title:'WASSUP2'
},
screen:AddBook
}
})
And finally here we come with Tab implementation.
const Tab = createBottomTabNavigator({
Home: {
screen: firstTabStack,
navigationOptions:{
title:'title1'
}
},
Another: {
screen: secondTabStack,
navigationOptions:{
title:'title2'
}
}
});
What did I do with these code?
For iOS Developers to get understand what is going on in there, there is a 2 Controller (UIViewController or Component in RN), and these have different UINavigationController's and also different titles. And all of these controllers will going to stack of the UITabBarController' viewControllers.
The images in below are proof of the successfully running.
,
I started out a bit with react-native, and I'm trying to make a "hello word" app to see how it works.
I made a menu with "tab" at the top of my screen
In the app.js I'm adding the createStackNavigator to set my routes
App.js
import { ... }
const AppNavigator = createStackNavigator({
Main: { screen: Main},
CScreen: {screen: FormCScreen},
});
type Props = {};
export default class App extends Component<Props> {
render() {
return (
<AppNavigator />
);
}
}
This is my main screen, where I set the tabs.
Main.js
imports {AScreen, BScreen} ...
const Tab = createMaterialTopTabNavigator(
{
A: AScreen,
B: BScreen,
},
{
tabBarPosition: 'top',
});
export default class Main extends Component {
render() {
return (
<Tab/>
);
}
}
BScreen.js
Now on one of my BScreen tabs, I want to click on a button, where I hope it loads the screen (CScreen)
imports ...
export default class BScreenextends Component{
render(){
return(
<View>
<TouchableHighlight onPress={() => this.props.navigation.navigate('CScreen')}>
<Text>Click here to open CScreen</Text>
</TouchableHighlight>
</View>
);
}
}
It can render all components correctly, the only problem is that when I click the button to display the CScreen, nothing happens.
It is as if loading the Tab I lost the instacia of my navigator.
Main
Tab
A
B Button (Open CScreen) ~> this is not working
How can I open the screen through a button inside a tab?
[EDIT]
Console.log ScreenB
https://imgur.com/a/teAzpn5
I think your trying to achieve StacksOverTabs mode of navigation setup,
The mistake you made is Main screen being a normal Component inside which you have rendered the Tab Component i.e createMaterialTopTabNavigator. Hence the Tab Component will not get the correct navigation prop from the StackNavigator
Instead, you have to make Main screen itself a createMaterialTopTabNavigator.
For example,
const AppNavigator = createStackNavigator({
Main: { screen: MainTab}, // MainTab is itself a TabNavigator now
CScreen: {screen: FormCScreen},
});
const MainTab = createMaterialTopTabNavigator(
{
A: AScreen,
B: BScreen,
},
{
tabBarPosition: 'top',
});
);
Check out the official examples code in GitHub, inside that navigate to StacksOverTabs
https://github.com/react-navigation/react-navigation/tree/master/examples/NavigationPlayground/js
Thanks.
You could also have put this at the top of your App class I believe:
static router = AppNavigator.router;
There is more information here: https://reactnavigation.org/docs/en/common-mistakes.html#explicitly-rendering-more-than-one-navigator
Having a bit of a struggle with understanding how to properly implement navigation in RN. The following code should be enough to see the current situation.
HeaderConnected is a component with a menu button which has a custom navigate prop to be able to open the Drawer menu (However, I believe this is not a proper way to pass navigate).
– Problem
HeaderConnected is in Main.js
– Expected
HeaderConnected to be above Navigator
App.js
// ...
import { DrawerNavigator } from "react-navigation";
export const Navigator = DrawerNavigator({
Main: { screen: Main },
Edit: { screen: EditScreen },
});
export default class App extends React.Component {
render() {
return (
<Provider store={createStore(reducer)}>
<Navigator />
</Provider>
);
}
}
Main.js
export class Main extends React.PureComponent {
static navigationOptions = {
drawerLabel: "Main",
};
render() {
return (
<View style={styles.container}>
<HeaderConnected
navigate={this.props.navigation.navigate}
/> // <--- This should be moved above <Navigator /> in App.js
<PostsConnected />
</View>
);
}
}
Of course, you could create another wrapper to hold both Navigator and HeaderConnected which you would then pass to Provider. However, this didn't work for me.
After reading react-navigator docs it seems there are several ways to handle this, alas not sure what would be the best/optimal way.
I had this problem in a recent project and worked it around by building a wrapper as you said, try using this code:
const mapNavigationStateParamsToProps = (SomeComponent) => {
return class extends Component {
static navigationOptions = SomeComponent.navigationOptions; // better use hoist-non-react-statics
render() {
const { navigation: { state: { params } } } = this.props
return (
<View style={{ flex: 1 }}>
<HeaderConnected
navigate={this.props.navigation.navigate}
/>
<SomeComponent {...params} {...this.props} />
</View>
)
}
}
}
then on your Navigator:
export const Navigator = DrawerNavigator({
Main: { screen: mapNavigationStateParamsToProps(Main) },
Edit: { screen: mapNavigationStateParamsToProps(EditScreen) },
});
I'm not sure if it is the best/optimal way, but it works for me.
Im following this tutorial https://reactnavigation.org/docs/intro/ and im running into a bit of issues.
Im using the Expo Client app to render my app every time and not a simulator/emulator.
my code is seen down below.
I originally had the "SimpleApp" const defined above "ChatScreen" component but that gave me the following error:
Route 'Chat' should declare a screen. For example: ...etc
so I moved the decleration of SimpleApp to just above "AppRegistry" and that flagged a new error
Element type is invalid: expected string.....You likely forgot to export your component..etc
the tutorial did not add the key words "export default" to any component which I think it may have to do with the fact that im running it on the Expo app? so I added "export default" to "HomeScreen" and the error went away.
The new error that I cant seem to get rid off(based on the code below) is the following:
undefined is not an object (evaluating 'this.props.navigation.navigate')
I can't get rid of it unless I remove the "{}" around "const {navigate}" but that will break the navigation when I press on the button from the home screen
import React from 'react';
import {AppRegistry,Text,Button} from 'react-native';
import { StackNavigator } from 'react-navigation';
export default class HomeScreen extends React.Component {
static navigationOptions = {
title: 'Welcome',
};
render() {
const { navigate } = this.props.navigation;
return (
<View>
<Text>Hello, Chat App!</Text>
<Button
onPress={() => navigate('Chat')}
title="Chat with Lucy"
/>
</View>
);
}
}
class ChatScreen extends React.Component {
static navigationOptions = {
title: 'Chat with Lucy',
};
render() {
return (
<View>
<Text>Chat with Lucy</Text>
</View>
);
}
}
const SimpleApp = StackNavigator({
Home: { screen: HomeScreen },
Chat: { screen: ChatScreen },
});
AppRegistry.registerComponent('SimpleApp', () => SimpleApp);
Additional Info:
When you are nesting child components, you need to pass navigation as prop in parent component.
//parent.js
<childcomponent navigation={this.props.navigation}/>
And you can access navigation like this
//child.js
this.props.navigation.navigate('yourcomponent');
Reference: https://reactnavigation.org/docs/en/connecting-navigation-prop.html
With Expo you should't do the App registration your self instead you should let Expo do it, keeping in mind that you have to export default component always:
Also you need to import View and Button from react-native: please find below the full code:
import React from 'react';
import {
AppRegistry,
Text,
View,
Button
} from 'react-native';
import { StackNavigator } from 'react-navigation';
class HomeScreen extends React.Component {
static navigationOptions = {
title: 'Welcome',
};
render() {
const { navigate } = this.props.navigation;
return (
<View>
<Text>Hello, Chat App!</Text>
<Button
onPress={() => navigate('Chat', { user: 'Lucy' })}
title="Chat with Lucy"
/>
</View>
);
}
}
class ChatScreen extends React.Component {
// Nav options can be defined as a function of the screen's props:
static navigationOptions = ({ navigation }) => ({
title: `Chat with ${navigation.state.params.user}`,
});
render() {
// The screen's current route is passed in to `props.navigation.state`:
const { params } = this.props.navigation.state;
return (
<View>
<Text>Chat with {params.user}</Text>
</View>
);
}
}
const SimpleAppNavigator = StackNavigator({
Home: { screen: HomeScreen },
Chat: { screen: ChatScreen }
});
const AppNavigation = () => (
<SimpleAppNavigator />
);
export default class App extends React.Component {
render() {
return (
<AppNavigation/>
);
}
}
As Bobur has said in his answer, the navigation prop isn't passed to children of the routed component. To give your components access to navigation you can pass it as a prop to them, BUT there is a better way.
If you don't want to pass the navigation prop all the way down your component hierarchy, you can use useNavigation instead. (Which in my opinion is just cleaner anyways, and reduces the amount of code we have to write):
function MyBackButton() {
const navigation = useNavigation();
return (
<Button
title="Back"
onPress={() => {
navigation.goBack();
}}
/>
);
}
https://reactnavigation.org/docs/use-navigation/
This is just really nice because if you have multiple levels of components you wont have to continuously pass the navigation object as props just to use it. Passing navigation just once requires us to 1. Add a prop to the component we want to pass it to. 2. Pass the prop from the parent component. 3. Use the navigation prop to navigate. Sometimes we have to repeat steps 1 and 2 to pass the prop all the way down to the component that needs to use navigation. We can condense steps 1 and 2, no matter how many times they are repeated, into a single useNavigation call with this method.
I think it is best.
Try this Code: onPress={() => this.props.navigation.navigate('Chat')}
<ChildComponent navigation={props.navigation} {...data} />
This will make the navigation from the parent propagated to the subsequent child navigations.
const AppNavigation =()=>{ <SimpleApp />}
export default class App extends React.Componet{
render(){
return (
<AppNavigation/>
);
}
}