my head is crack up now with this navigation, i watched several videos about this and follow them but still hitting the same error of undefined is not an object error for this.props.navigation.navigate
here is my code basically
App.js
import React from 'react';
import { Container, Body, Header, Title, Content, List, ListItem, Text, Left, Right, Icon, Footer, FooterTab, Button} from 'native-base';
import { createStackNavigator } from 'react-navigation';
import { YellowBox } from 'react-native';
YellowBox.ignoreWarnings(['Warning: isMounted(...) is deprecated', 'Module RCTImageLoader']);
import Home from './Home';
import Details from './Details';
export default createStackNavigator(
{
Home: {
screen: Home
},
Details: {
screen: Details
}
},
{
initialRouteName: 'Home',
}
);
Here is my Home.js
import React, { Component } from 'react';
import { Container, Body, Header, Title, Content, List, ListItem, Text, Left, Right, Icon, Footer, FooterTab, Button} from 'native-base';
class Home extends Component {
constructor(){
super();
this.state = {
data: []
};
}
getData(){
return fetch('https://testdata.com')
.then((response) => response.json())
.then((responseJson) => {
console.log(JSON.stringify(responseJson.result));
this.setState({data:responseJson.result});
//alert(responseJson.result[1].name);
//return responseJson.result[1].name;
})
.catch((error) => {
console.error(error);
});
}
componentDidMount(){
this.getData();
}
static navigationOptions = ({navigation}) => {
const {state, navigate} = navigation;
return {
title: "test",
headerStyle: {
backgroundColor: '#4050B5',
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold'
},
};
};
render() {
let yytCardData = this.state.data.map(function(cardData, i){
return (
<ListItem key={cardData.ver}>
<Left>
<Text>{cardData.name}</Text>
</Left>
<Right>
<Icon name="arrow-forward" />
<Button transparent info onPress={() => this.props.navigation.navigate('Details')}>
<Text>Info</Text>
</Button>
</Right>
</ListItem>
)
});
return (
<Container>
<Content>
<List>
{yytCardData}
</List>
</Content>
<Footer>
<FooterTab>
<Button vertical active>
<Icon name="apps" />
<Text>Title List</Text>
</Button>
<Button vertical>
<Icon name="search" />
<Text>Search</Text>
</Button>
</FooterTab>
</Footer>
</Container>
);
}
}
export default Home
and a very empty Details.js
import React, { Component } from 'react';
import { Container, Header, Content, List, ListItem, Text, Left, Right, Icon } from 'native-base';
class Details extends Component {
render() {
return(
<Container>
<Header />
<Content padder>
<Card transparent>
<CardItem>
<Body>
<Text>
This is just a transparent card with some text to boot.
</Text>
</Body>
</CardItem>
</Card>
</Content>
</Container>
);
}
}
export default Details;
i am not sure which part is incorrect in this case but doing just a simple navigation sounds very complex
You need to bind your function using the arrow function in your render method.
let yytCardData = this.state.data.map((cardData, i) => { // Replace function with arrow function
The issue is with scope in Home component this.state.data.map(function(cardData, i){. If you don't want to use arrow function then you can use the same function but just assigning this to a local variable and use that
let yytCardData = this.state.data.map(function(cardData, i){
let that = this;
return (
<ListItem key={cardData.ver}>
<Left>
<Text>{cardData.name}</Text>
</Left>
<Right>
<Icon name="arrow-forward" />
<Button transparent info onPress={() => that.props.navigation.navigate('Details')}>
<Text>Info</Text>
</Button>
</Right>
</ListItem>
)
});
If you want to use arrow function then follow what Pritish Vaidya mentioned
Related
I would like to implement scrolling to top. My tab is a flatlist, and when users scroll down the flatlist, they have to scroll back up. Instagram and Twitter allow you to press the tab to scroll back up, I am wondering how to implement it in my own app.
Here is the tab I want to implement scrolling to top:
//Bottom Tabs
function Tabs() {
...
<Tab.Screen
name="Home"
component={globalFeedStackView}
options={{
tabBarLabel: ' ',
tabBarIcon: ({ color, size }) => (
<Ionicons name="ios-home" size={size} color={color} />
),
}}
/>
}
And the class component for the tab above:
class GlobalScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
globalPostsArray: [],
navigation: this.props.navigation,
};
}
async componentDidMount() {
this.getCollection()
Analytics.setUserId(Firebase.auth().currentUser.uid)
Analytics.setCurrentScreen("GlobalScreen")
}
...
render() {
return (
<View style={styles.view}>
<FlatList
data={this.state.globalPostsArray}
renderItem={renderItem}
keyExtractor={item => item.key}
contentContainerStyle={{ paddingBottom: 50 }}
showsHorizontalScrollIndicator={false}
showsVerticalScrollIndicator={false}
onRefresh={this._refresh}
refreshing={this.state.isLoading}
onEndReached={() => {this.getMore()}}
/>
<KeyboardSpacer />
</View>
)
}
According to react navigation I can do something like this:
import * as React from 'react';
import { ScrollView } from 'react-native';
import { useScrollToTop } from '#react-navigation/native';
class Albums extends React.Component {
render() {
return <ScrollView ref={this.props.scrollRef}>{/* content */}</ScrollView>;
}
}
// Wrap and export
export default function(props) {
const ref = React.useRef(null);
useScrollToTop(ref);
return <Albums {...props} scrollRef={ref} />;
}
But this solution is for a scrollview, and I am using a flatlist.
How can I implement pressing a tab to scroll to the top of my flatlist?
scrollToOffset
you can do it the same way with a ref on your FlatList :
import * as React from 'react';
import { FlatList } from 'react-native';
class Albums extends React.Component {
render() {
return <FlatList ref={this.props.scrollRef} />;
}
// Wrap and export
export default function(props) {
const ref = React.useRef(null);
ref.scrollToOffset({ animated: true, offset: 0 });
return <Albums {...props} scrollRef={ref} />;
}
I want to go out of top tab navigation but it unable to navigate. It's giving error The action 'NAVIGATE' with payload {"name":"LoginPage"} was not handled by any navigator.
Do you have a screen named 'LoginPage'?
If you're trying to navigate to a screen in a nested navigator, see https://reactnavigation.org/docs/nesting-navigators#navigating-to-a-screen-in-a-nested-navigator
I use nesting navigation also but not work. My Screens are below
Top tab navigation screen
import * as React from 'react';
import { Text, View } from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import { createMaterialTopTabNavigator } from '#react-navigation/material-top-tabs';
import {widthPercentageToDP as wp, heightPercentageToDP as hp} from 'react-native-responsive-screen';
import ProfileData from './profiledata';
import ProfileLikeData from './profilelikedata';
import Fontisto from 'react-native-vector-icons/Fontisto';
const Tab = createMaterialTopTabNavigator();
export default function App() {
return (
<NavigationContainer>
<Tab.Navigator
screenOptions={({ route }) => ({
tabBarIcon: ({ focused, color }) => {
let iconName;
let size;
if (route.name === 'Data') {
iconName = focused
? 'nav-icon-grid'
: 'nav-icon-grid';
size = focused
? 25
: 25;
} else if (route.name === 'Like') {
iconName = focused ? 'heart' : 'heart';
size = focused
? 20
: 20;
}
return <Fontisto name={iconName} size={size} color={color} />;
},
})}
tabBarOptions={{
activeTintColor: '#d40786',
inactiveTintColor: 'white',
showIcon:true,
showLabel:false,
indicatorStyle: {
width: 0, height: 0, elevation: 0,
},
tabStyle: { width: wp('52%'),borderRightWidth:1,borderColor:'white' },
style: { backgroundColor:'trasparent',borderTopWidth:0.5,borderColor:'white',paddingBottom:5 },
}}
>
<Tab.Screen name="Data" component={ProfileData} />
<Tab.Screen name="Like" component={ProfileLikeData} />
</Tab.Navigator>
</NavigationContainer>
);
}
profiledata.js
import React from 'react';
import { View, StyleSheet, Text,ImageBackground,TouchableOpacity,Image } from 'react-native';
import { FlatGrid } from 'react-native-super-grid';
import {widthPercentageToDP as wp, heightPercentageToDP as hp} from 'react-native-responsive-screen';
import { RFPercentage, RFValue } from "react-native-responsive-fontsize";
import Toast from 'react-native-simple-toast';
export default class ProfileData extends React.Component {
constructor(props) {
super(props);
this.state = {
videos:[],
loginid:'',
paused:true,
};
}
static navigationOptions = {
headerShown: false,
};
render() {
const { navigate } = this.props.navigation;
return (
<View style={styles.container}>
<FlatGrid
data={this.state.videos}
spacing={0}
renderItem={({ item }) => (
<TouchableOpacity onPress={()=>navigate('LoginPage')} style={{flex:1}}>
// some data
</TouchableOpacity>
)}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex:1,
// paddingHorizontal:wp('2%'),
backgroundColor:'black',
height: hp('100%'),
},
});
You should create another stack that has your login screen or add the login screen in the tab navigator.
for the first do something like this in your app.js
import { createStackNavigator } from '#react-navigation/stack';
import LoginScreen from './LoginScreen'; //Just import the login screen
const AuthStack = createStackNavigator();
const AuthStackScreen = () => (
<AuthStack.Navigator>
<AuthStack.Screen
name="LoginPage"
component={LoginScreen}
/>
</AuthStack.Navigator>
);
//Then in your profiledata.js;
<TouchableOpacity onPress={()=>navigate('LoginPage')} style={{flex:1}}>
// some data
</TouchableOpacity>
And for the second option just add the login screen in your tab navigator;
<Tab.Screen name="Data" component={ProfileData} />
<Tab.Screen name="Like" component={ProfileLikeData} />
<Tab.Screen name="LoginPage" component={LoginScreen} /> //Don't forget to import it
I am currently doing ReactNative course from coursera and the course is 4 years old and i am facing this error: Touchable child must either be native or forward setNativeProps to a native component.
I've no idea what this is. It will be greatly helpful if someone will help me.Adding files details as well:
App.js
import React from 'react';
import Main from './components/MainComponent';
export default class App extends React.Component {
render() {
return (
<Main />
);
}
}
MainComponent.js
import React, { Component } from 'react';
import Menu from './MenuComponent';
import { DISHES } from '../shared/dishes';
import Dishdetail from './DishdetailComponent';
import { View } from 'react-native';
class Main extends Component {
constructor(props) {
super(props);
this.state = {
dishes: DISHES,
selectedDish: null,
};
}
onDishSelect(dishId) {
this.setState({selectedDish: dishId})
}
render() {
return (
<View style={{flex:1}}>
<Menu dishes={this.state.dishes} onPress={(dishId) => this.onDishSelect(dishId)} />
<Dishdetail dish={this.state.dishes.filter((dish) => dish.id === this.state.selectedDish)[0]} />
</View>
);
}
}
export default Main;
MenuComponent.js
import React from 'react';
import { View, FlatList } from 'react-native';
import { ListItem } from 'react-native-elements';
function Menu(props) {
const renderMenuItem = ({item, index}) => {
return (
<View>
<ListItem
key={index}
title={item.name}
subtitle={item.description}
hideChevron={true}
onPress={() => props.onPress(item.id)}
leftAvatar={{ source: require('./images/uthappizza.png')}}
/>
</View>
);
};
return (
<View>
<FlatList
data={props.dishes}
renderItem={renderMenuItem}
keyExtractor={item => item.id.toString()}
/>
</View>
);
}
export default Menu;
Dishdetailcomponent.js
import React from 'react';
import { Text, View } from 'react-native';
import { Card } from 'react-native-elements';
function Dishdetail(props) {
return(
<View >
<RenderDish dish={props.dish} />
</View>
);
}
function RenderDish(props) {
const dish = props.dish;
if (dish != null) {
return(
<View>
<Card
featuredTitle={dish.name}
image={require('./images/uthappizza.png')}>
<Text style={{margin: 10}}>
{dish.description}
</Text>
</Card>
</View>
);
}
else {
return(<View></View>);
}
}
export default Dishdetail;
Help will be appreciated!!
Thanks
I had same issue some days before. Quickfix for this issue.
import TouchableOpacity form 'react-native';
Add following in the MenuComponent.js
<ListItem
Component={TouchableOpacity}
key={item.id}
title={item.name}
subtitle={item.description}
hideChevron={true}
onPress={() => props.onPress(item.id)}
leftAvatar={{ source: require('./images/uthappizza.png')}}
/>
and run the program again. This will fix your problem.
when i swipe right my drawer open but i want to open it using a button in the header i did a code but i have this error undefined is not a object (evaluating 'navigation.openDrawer')
thats my app.js code :
import {createStackNavigator} from 'react-navigation-stack';
import { createAppContainer } from 'react-navigation';
import Home from './components/login'
import Inscription from './components/inscription'
import signup from './components/signup'
import mp from './components/motdepasse'
import ch from './components/choice'
import mn from './components/menu1'
import drawer from './components/drawerapp'
import React, { Component } from 'react';
import { Image, StyleSheet, Text, TouchableOpacity, } from 'react-native';
import Icon from 'react-native-vector-icons/Entypo'
const Navigator = createStackNavigator({
Home:{screen: Home},
Profil:{screen: Inscription},
signup:{screen: signup, navigationOptions: { header: null }},
mp:{screen: mp},
ch:{screen: ch},
mn:{screen: mn},
drawer:{screen: drawer,navigationOptions: { title:"votre travail",
headerStyle:{backgroundColor:'#8B0000'},
headerTitleStyle: {
fontWeight: 'bold',
color:'white',
},
headerLeft: ({ navigation }) => (
<TouchableOpacity onPress={() => navigation.openDrawer()} >
<Icon name={'menu'} size={28} color={'white'} style={{marginRight:10}}/>
</TouchableOpacity>
),}},
}
);
const App = createAppContainer(Navigator);
export default App;
and that's my appdrawer code:
function CustomDrawerContent(props) {
return (
<DrawerContentScrollView {...props}>
<DrawerItemList {...props} />
<DrawerItem label="Help" onPress={() => alert('Link to help')} />
<DrawerItem
label="Close drawer"
onPress={() => props.navigation.closeDrawer()}
/>
</DrawerContentScrollView>
);
}
const Drawer = createDrawerNavigator();
function MyDrawer() {
return (
<Drawer.Navigator drawerContent={props => CustomDrawerContent(props)}>
<Drawer.Screen name="Feed" component={mn} />
<Drawer.Screen name="Article" component={Article} />
</Drawer.Navigator>
);
}
export default class drawerapp extends React.Component {
render(){
const {navigate} = this.props.navigation;
return (
<NavigationContainer>
<MyDrawer />
</NavigationContainer>
);
}}
my work perfectly fine until i click on the left header button and the error appear
u are getting the navigation prop in wrong place, headerLeft does not give navigation prop, so u have to get it from navigationOptions...
change the navigator code as below..
const Navigator = createStackNavigator({
Home:{screen: Home},
Profil:{screen: Inscription},
signup:{screen: signup, navigationOptions: { header: null }},
mp:{screen: mp},
ch:{screen: ch},
mn:{screen: mn},
drawer:{screen: drawer,
navigationOptions: ({navigation}) => ({
title:"votre travail",
headerStyle:{backgroundColor:'#8B0000'},
headerTitleStyle: {
fontWeight: 'bold',
color:'white',
},
headerLeft: () => (
<TouchableOpacity onPress={() => navigation.openDrawer()} >
<Icon name={'menu'} size={28} color={'white'} style={{marginRight:10}}/>
</TouchableOpacity>
),
}),
},
});
When I add the <Menu /> component to my header as below:
let SearchPage = (props) => {
const menu = (
<Container>
<Header style={styles.header}>
<Left>
<Button >
<Menu />
</Button>
</Left>
<Body>
I get the error
Maximum call stack size exceeded
and of course if I comment out the <Menu /> line in my SearchPage, there is no error.
The menu is a react-native-off-canvas-menu
My menu component:
components/menu/Menu.js
import React from 'react'
import { View, Icon } from 'react-native'
import { connect } from 'react-redux'
import { togglePageMenu } from './menu.action'
import { OffCanvas3D } from 'react-native-off-canvas-menu'
//import AddPage from '../add-page/AddPage'
import SearchPage from '../search-page/SearchPage'
const mapStateToProps = (state) => ({
isOpen: state.get('menu').isOpen
})
const mapDispatchToProps = (dispatch) => ({
togglePageMenu: () => {
dispatch(togglePageMenu())
}
})
let Menu = (props) => (
<View style={{ flex: 1 }}>
<OffCanvas3D
active={props.isOpen}
onMenuPress={props.togglePageMenu}
backgroundColor={'#222222'}
menuTextStyles={{ color: 'white' }}
handleBackPress={true}
menuItems={[
{
title: 'Search Products',
icon: <Icon name="camera" size={35} color='#ffffff' />,
renderScene: <SearchPage />
}
]} />
</View>
)
Menu.propTypes = {
togglePageMenu: React.PropTypes.func.isRequired,
isOpen: React.PropTypes.bool.isRequired
}
Menu = connect(
mapStateToProps,
mapDispatchToProps
)(Menu)
export default Menu
What could be causing the error?
Here is my component that uses the menu (probably not relevant):
components/search-page/SearchPage.js
import { ScrollView, StyleSheet, View } from 'react-native'
import {
Container,
Button,
Text,
Header,
Body,
Right,
Left,
Title,
Icon
} from 'native-base'
import React from 'react'
import Keywords from '../keywords/Keywords'
import Categories from '../categories/Categories'
import Location from '../location/Location'
import Menu from '../menu/Menu'
import DistanceSlider from '../distanceSlider/DistanceSlider'
import Map from '../map/Map'
import Drawer from 'react-native-drawer'
import { connect } from 'react-redux'
import { toggleMenu } from './searchPage.action'
import { styles, wideButtonColor } from '../../style'
import searchPageStyle from './style'
import { selectIsSearchFormValid } from './isSearchFormValid.selector'
const mapStateToProps = (state) => ({
isMenuOpen: state.get('searchPage').get('isMenuOpen'),
isSearchFormValid: selectIsSearchFormValid(state)
})
const mapDispatchToProps = (dispatch) => ({
toggleMenu: () => {
dispatch(toggleMenu())
}
})
let SearchPage = (props) => {
const menu = (
<Container>
<Header style={styles.header}>
<Left>
<Button >
<Menu />
</Button>
</Left>
<Body>
<Title style={styles.title}>Search Products</Title>
</Body>
<Right>
</Right>
</Header>
<Container style={styles.container}>
<ScrollView keyboardShouldPersistTaps={true}>
<Categories />
<View style={searchPageStyle.locationContainer}>
<Location />
</View>
<DistanceSlider />
<Keywords />
<Button
block
style={{
...searchPageStyle.goButton,
backgroundColor: wideButtonColor(!props.isSearchFormValid)
}}
disabled={!props.isSearchFormValid}
onPress={props.toggleMenu}>
<Text>GO</Text>
</Button>
</ScrollView>
</Container>
</Container>
)
return (
<Drawer open={props.isMenuOpen} content={menu}>
<Container style={mapStyles.container}>
<Map />
</Container>
</Drawer>
)
}
SearchPage.propTypes = {
toggleMenu: React.PropTypes.func.isRequired,
isMenuOpen: React.PropTypes.bool.isRequired,
isSearchFormValid: React.PropTypes.bool.isRequired
}
SearchPage = connect(
mapStateToProps,
mapDispatchToProps
)(SearchPage)
export default SearchPage
const mapStyles = StyleSheet.create({
container: {
...StyleSheet.absoluteFillObject,
height: 400,
width: 400,
justifyContent: 'flex-end',
alignItems: 'center',
}
})
It's because you are rendering another <SearchPage /> within your menu: renderScene: <SearchPage />. This creates a circular dependency where a SearchPage is creating a Menu and the Menu is creating a SearchPage... etc. Until, as you saw, you run out of memory.