react native, moving between screens - react-native

I am using stackNavigator in react native .my problem is I want to move to another screen using stack navigator.
app.js
const CartStack=createStackNavigator({
Header:Header,
Cart:Cart
)}
Const Root=createStackNavigator({
Home:Home,
Detail:Detail,
CartStack:CartStack,
)}
Home.js
render() {
return (
<Header/>
)}
The Header Will be show on both screens (Home and Detail)
in the header i created a cart button which i want to click on
it then will be open a Cart screen. But my code is not working.
Please correct my code.

The concept in Zayco's answer is absolutely correct.
But I figured out that this.props.navigation.navigate will be undefined in navigationOptions
Here is the working example of your requirement.
class Home extends React.Component {
static navigationOptions = ({navigation}) => ({
title: 'Home',
headerRight:(<Button title="Cart" onPress={() => navigation.navigate('Cart')}/>)
})
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Scree</Text>
<Button
title="Go to Details"
onPress={() => this.props.navigation.navigate('Details')}
/>
</View>
);
}
}
class Details extends React.Component {
static navigationOptions = ({navigation}) => ({
title: 'Details',
headerRight:(<Button title="Cart" onPress={() => navigation.navigate('Cart')}/>)
})
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Details</Text>
</View>
);
}
}
class Cart extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Cart</Text>
</View>
);
}
}
const RootStack = createStackNavigator(
{
Home: Home,
Details: Details,
Cart:Cart
},
{
initialRouteName: 'Home',
}
);

This is taken from the React Navigation documentation
You have 3 screens: Home, Details and Cart. In the header of Home and Details you have a button that will take you to the Cart screen. I suggest you take a look at the Fundementals section of the documentation.
Here is the working Snack
import React from "react";
import { View, Text, Button } from "react-native";
import { createStackNavigator, createAppContainer } from "react-navigation";
class HomeScreen extends React.Component {
static navigationOptions = ({ navigation }) => ({
headerTitle: "Home",
headerRight: (
<Button
onPress={() => navigation.navigate('Cart')}
title="Cart"
color="blue"
/>
)
});
render() {
return (
<View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
<Text>Home Screen</Text>
<Button
onPress={() => this.props.navigation.navigate('Details')}
title="Go to details"
color="red"
/>
</View>
);
}
}
class DetailsScreen extends React.Component {
static navigationOptions = ({ navigation }) => ({
headerTitle: "Details",
headerRight: (
<Button
onPress={() => navigation.navigate('Cart')}
title="Cart"
color="blue"
/>
),
});
render() {
return (
<View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
<Text>Details Screen</Text>
<Button
onPress={() => this.props.navigation.navigate('Home')}
title="Go to home"
color="red"
/>
</View>
);
}
}
class CartScreen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
<Text>Cart Screen</Text>
</View>
);
}
}
const AppNavigator = createStackNavigator(
{
Home: HomeScreen,
Details: DetailsScreen,
Cart: CartScreen
},
{
initialRouteName: "Home"
}
);
export default createAppContainer(AppNavigator);

Related

How to show footer in full screen

I have a footer that contains several buttons that I want to show in full screen. I'm using below code:
**//App.js**
export default class App extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<View style={{flex: 1, backgroundColor: '#6ED4C8'}}>
<AppNavigator />
<View style={{flexDirection: 'row'}}>
<Footer />
</View>
</View>
);
}
}
**//AppNavigator.js**
const AppNavigator = createStackNavigator(
{
Home: {screen: Home},
Friends: {screen: Friends},
Login: {screen: Login},
PostDatiles: {screen: PostDatiles},
Aboutus: {screen: Aboutus},
Footer: {screen: Footer},
},
{
headerMode: 'none',
navigationOptions: {
headerVisible: false,
},
// ,initialRouteName: ''
},
);
export default AppNavigator;
**//Footer.js**
export default class Footer extends React.Component {
constructor(props) {
super(props);
}
render() {
const {navigation} = this.props;
return (
<View style={styles.container}>
<View>
<Button
title="About us"
color="#39F80F"
accessibilityLabel="Tap on Me"
onPress={() => navigation.navigate('Login')}
/>
</View>
<View>
<Button
title="Login"
color="#F8380F"
accessibilityLabel="Tap on Me"
/>
</View>
<View>
<Button
title="Search"
color="#B80FF8"
accessibilityLabel="Tap on Me"
/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
},
});
When I click on one of the buttons, I get this error:
enter image description here
In the app.js file I use a footer tag because I want show it on all of the screen.
I searched a lot but couldn't find any similar problem!
To do what you want to do, you must use the createBottomTabNavigator instead of the StackNavigator.
Example
import React from 'react';
import { Text, View } from 'react-native';
import { Ionicons } from '#expo/vector-icons'; // 6.2.2
import { createBottomTabNavigator, createAppContainer } from 'react-navigation';
class HomeScreen extends React.Component {
render() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Home!</Text>
</View>
);
}
}
class SettingsScreen extends React.Component {
render() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Settings!</Text>
</View>
);
}
}
class IconWithBadge extends React.Component {
render() {
const { name, badgeCount, color, size } = this.props;
return (
<View style={{ width: 24, height: 24, margin: 5 }}>
<Ionicons name={name} size={size} color={color} />
{badgeCount > 0 && (
<View
style={{
// /If you're using react-native < 0.57 overflow outside of the parent
// will not work on Android, see https://git.io/fhLJ8
position: 'absolute',
right: -6,
top: -3,
backgroundColor: 'red',
borderRadius: 6,
width: 12,
height: 12,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text style={{ color: 'white', fontSize: 10, fontWeight: 'bold' }}>
{badgeCount}
</Text>
</View>
)}
</View>
);
}
}
const HomeIconWithBadge = props => {
// You should pass down the badgeCount in some other ways like context, redux, mobx or event emitters.
return <IconWithBadge {...props} badgeCount={3} />;
};
const getTabBarIcon = (navigation, focused, tintColor) => {
const { routeName } = navigation.state;
let IconComponent = Ionicons;
let iconName;
if (routeName === 'Home') {
iconName = `ios-information-circle${focused ? '' : '-outline'}`;
// We want to add badges to home tab icon
IconComponent = HomeIconWithBadge;
} else if (routeName === 'Settings') {
iconName = `ios-options${focused ? '' : '-outline'}`;
}
// You can return any component that you like here!
return <IconComponent name={iconName} size={25} color={tintColor} />;
};
export default createAppContainer(
createBottomTabNavigator(
{
Home: { screen: HomeScreen },
Settings: { screen: SettingsScreen },
},
{
defaultNavigationOptions: ({ navigation }) => ({
tabBarIcon: ({ focused, tintColor }) =>
getTabBarIcon(navigation, focused, tintColor),
}),
tabBarOptions: {
activeTintColor: 'tomato',
inactiveTintColor: 'gray',
},
}
)
);

Adding menu button for Navigation drawer gives error

I've searched how to setup a button to make the drawer action on Stackoverflow for my react-native project and followed as per answers, but still it is not working. Some answers, it simply didn't work, but sometimes it is giving error (Invariant violation error). But the sliding action for opening up the drawer is working, still I want to include button for navigation drawer. I referred this link : Add hamburger button to React Native Navigation
Here is my code, I'm sorry it is too large.
import React, { Component } from 'react';
import {
StyleSheet, Text,
View, TextInput,
Button, TouchableHighlight,
TouchableOpacity, Image,
Alert, ImageBackground,
Platform, YellowBox,
Dimensions, Keyboard,
TouchableWithoutFeedback, AsyncStorage,
ActivityIndicator, FlatList,
ScrollView
} from 'react-native';
import { createStackNavigator, createAppContainer,createDrawerNavigator, DrawerToggle, DrawerNavigator, DrawerActions, StackNavigator } from "react-navigation";
import { Container, Content, ListItem, List } from "native-base";
class Hidden extends React.Component {
render() {
return null;
}
}
const DismissKeyboard = ({ children }) => (
<TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
{children}
</TouchableWithoutFeedback>
);
class LoginView extends Component {
static navigationOptions = {
header: null,
};
constructor(props) {
super(props);
this.myTextInput1 = React.createRef();
this.myTextInput2 = React.createRef();
this.state = {
email : '',
password: '',
};
let keys = ['email', 'password'];
AsyncStorage.multiRemove(keys, (err) => {
console.log('Local storage user info removed!');
});
}
onClickListener = (viewId) => {
Alert.alert("Help", "Contact Admin for "+viewId);
}
validateEmail = (email) => {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
};
loginNext = ()=>{
AsyncStorage.multiSet([
["email", this.state.email],
["password", this.state.password]
]);
this.setState({
email : '',
password: '',
});
this.myTextInput1.current.clear();
this.myTextInput2.current.clear();
Keyboard.dismiss();
if (this.validateEmail(this.state.email)){
this.props.navigation.navigate('profile');
}
else{
Alert.alert('Warning','Enter proper email!')
}
}
render() {
return (
<DismissKeyboard>
<ImageBackground source={require('./zbg_app_1.jpg')} style={{width: '100%', height: '100%'}}>
<View style={styles.container}>
<View style={styles.inputContainer}>
<Image style={styles.inputIcon} source={{uri: 'https://png.icons8.com/email/ultraviolet/50/3498db'}}/>
<TextInput style={styles.inputs}
placeholder="Email"
keyboardType="email-address"
underlineColorAndroid='transparent'
onChangeText={(email) => this.setState({email})}
ref = {this.myTextInput1}/>
</View>
<View style={styles.inputContainer}>
<Image style={styles.inputIcon} source={{uri: 'https://png.icons8.com/key-2/ultraviolet/50/3498db'}}/>
<TextInput style={styles.inputs}
placeholder="Password"
secureTextEntry={true}
underlineColorAndroid='transparent'
onChangeText={(password) => this.setState({password})}
ref = {this.myTextInput2}/>
</View>
<TouchableHighlight style={[styles.buttonContainer, styles.loginButton]} onPress={()=>{(this.state.email != '' && this.state.password != '') ?this.loginNext():Alert.alert('Warning','Empty Field(s)!')}}>
<Text style={styles.loginText}>Login</Text>
</TouchableHighlight>
<TouchableHighlight style={styles.buttonContainer} onPress={() => this.onClickListener('forgot_password')}>
<Text>Forgot your password?</Text>
</TouchableHighlight>
</View>
</ImageBackground>
</DismissKeyboard>
);
}
}
class ProfileView extends Component {
static navigationOptions = {
headerTitle: 'Profile',
};
constructor(props) {
super(props);
this.myTextInput1 = React.createRef();
this.state = {
loggedEmail :'',
loggedPassword: '',
city:''
}
}
submitNext = ()=>{
this.myTextInput1.current.clear();
Keyboard.dismiss();
Alert.alert('Information',this.state.city);
{/*AsyncStorage.setItem('city',this.state.city);
this.setState({
city:''
});
*/}
}
render() {
AsyncStorage.multiGet(['email', 'password']).then(data => {
let email = data[0][1];
let password = data[1][1];
if (email !== null){
this.setState({loggedEmail:email});
}
});
return (
<View style={{ flexDirection: 'column' , alignItems: 'center', justifyContent: 'center'}}>
<View style={{ flexDirection: 'column' , marginTop: 60, alignItems: 'center', justifyContent: 'center'}}>
<Text>{this.state.loggedEmail}</Text>
<Button onPress={()=> this.props.navigation.navigate('login')} title="Login Page"/>
</View>
{/*<View style={styles.container1}>
<View style={styles.inputContainer}>
<TextInput style={styles.inputs}
placeholder="Enter city"
underlineColorAndroid='transparent'
onChangeText={(city) => this.setState({city})}
ref = {this.myTextInput1}/>
</View>
<TouchableHighlight style={[styles.buttonContainer, styles.loginButton]} onPress={()=>{(this.state.city != '') ?this.submitNext():Alert.alert('Warning','Empty Field(s)!')}}>
<Text style={styles.loginText}>Submit</Text>
</TouchableHighlight>
</View>*/}
</View>
);
}
}
class Custom_Side_Menu extends Component {
render() {
return (
<View style={styles.sideMenuContainer}>
<Image source={{ uri: 'https://reactnativecode.com/wp-content/uploads/2017/10/Guitar.jpg' }}
style={styles.sideMenuProfileIcon} />
<View style={{ width: '100%', height: 1, backgroundColor: '#e2e2e2', marginTop: 15}} />
<View style={{width: '100%'}}>
<View style={{flexDirection: 'row', alignItems: 'center', marginTop: 10}}>
<Image source={{ uri: 'https://reactnativecode.com/wp-content/uploads/2018/08/social.jpg' }}
style={styles.sideMenuIcon} />
<Text style={styles.menuText} onPress={() => { this.props.navigation.navigate('First') }} > First Activity </Text>
</View>
<View style={{flexDirection: 'row', alignItems: 'center', marginTop: 10}}>
<Image source={{ uri: 'https://reactnativecode.com/wp-content/uploads/2018/08/promotions.jpg' }}
style={styles.sideMenuIcon} />
<Text style={styles.menuText} onPress={() => { this.props.navigation.navigate('Second') }} > Second Activity </Text>
</View>
<View style={{flexDirection: 'row', alignItems: 'center', marginTop: 10}}>
<Image source={{ uri: 'https://reactnativecode.com/wp-content/uploads/2018/08/outbox.jpg' }}
style={styles.sideMenuIcon} />
<Text style={styles.menuText} onPress={() => { this.props.navigation.navigate('Third') }} > Third Activity </Text>
</View>
</View>
<View style={{ width: '100%', height: 1, backgroundColor: '#e2e2e2', marginTop: 15}} />
</View>
);
}
}
class Fetch extends Component{
constructor(props){
super(props);
this.state ={ isLoading: true,};
}
componentDidMount(){
return fetch('http://d4abf7d9.ngrok.io/opdytat003/api/login/',
{
method: 'POST',
headers:{
Accept: 'application/json',
'Content-Type': 'application/json',
},
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson,
}, function(){
});
})
.catch((error) =>{
console.error(error);
});
}
render(){
console.log(this.state.dataSource)
if(this.state.isLoading){
return(
<View style={{flex: 1, padding: 20}}>
<ActivityIndicator/>
</View>
)
}
return(
<ScrollView style={{flex: 1, paddingTop:30}}>
{/*<FlatList
data={this.state.dataSource}
renderItem={({item}) => <Text>{item.title}, {item.releaseYear}</Text>}
keyExtractor={({id}, index) => id}
/>*/}
<Text>API => Zelthy API:</Text>
<Text>{JSON.stringify(this.state.dataSource.next_step)}</Text>
<Text>{JSON.stringify(this.state.dataSource.access_token)}</Text>
<Text>{JSON.stringify(this.state.dataSource.menu)}</Text>
<Text>{JSON.stringify(this.state.dataSource.detail)}</Text>
<Text>{JSON.stringify(this.state.dataSource.responsecode)}</Text>
<Text>{JSON.stringify(this.state.dataSource.refresh_token)}</Text>
</ScrollView>
);
}
}
const AppLogin = createStackNavigator({
login: {
screen: LoginView,
},
},
{
initialRouteName: "login"
}
);
const AppProfile = createStackNavigator({
profile: {
screen: ProfileView,
},
},
);
const Nav = createDrawerNavigator(
{
Home: {
screen: AppLogin,
navigationOptions:{
drawerLockMode: 'locked-closed',
drawerLabel: <Hidden />
},
},
Profile: {
screen: AppProfile
},
Activities: {screen: Custom_Side_Menu},
API: {screen: Fetch},
'Sign Out': {screen: LoginView},
},
{
contentOptions: {
activeTintColor: 'green',
inactiveTintColor: 'white',
},
drawerPosition: 'left',
drawerWidth: 200,
drawerBackgroundColor: 'purple',
initialRouteName: 'Home'
}
);
export default createAppContainer(Nav);
I've referred Github React Native issues links but it also didn't help in my case.
When I add this part of code in StackNavigator of Profile screen, I get this below output but no change on clicking.
navigationOptions: ({ navigation }) => ({
title: 'Profile', // Title to appear in status bar
headerLeft: <Button title='=' onPress={ () => navigation.navigate('DrawerOpen') } />
})
Screenshot:
https://reactnavigation.org/docs/en/drawer-navigator.html#drawernavigatorconfig
Add contentComponent in DrawerNavigatorConfig which displays actual side MenuBar and put hamburger on top-left of MenuBar if it slides from right and on top-right of MenuBar is it slides from left side of screen.
contentComponent is basically React Component, where you display list of items like Home, Profile, My orders, Logout etc, You can add your hamburger above all this options, somewhere in top corners.
In addition, Try replacing Button with TouchableOpacity. Also, first of all try logging something on console with onPress function of TouchableOpacity. If it is logging successfully only then attach navigation.navigate("xyz-screen"), also make sure that your navigation object has navigate method present in it. Sometimes this gives error because of undefined navigation object. If navigation object exist, the try using onPress = {navigation.openDrawer} instead of navigation.navigate("DrawerOpen").

React Native, fixed header and footer for entire app with Navigation Drawer

I need to create a React native app with Navigation Drawer, and i'm facing some problems.
I have 3 different screen:
"HomeScreen", "ScreenOne", "ScreenTwo", "ScreenThree" and this is how my code for navigators:
export const HomeNavigator = createStackNavigator({
Home : { screen : HomeScreen },
One: { screen : ScreenOne},
Two : { screen : ScreenTwo }
},{
unmountInactiveRoutes : true,
headerMode: 'none'
});
the above navigator is specific for HomeScreen, where user can navigate to screenOne or screenTwo by tapping some element inside it.
The navigator below is for entire app:
export const AppDrawerNavigator = createDrawerNavigator({
HomePage : {
screen:HomeNavigator,
navigationOptions: {
drawerLabel: 'Homepage',
drawerIcon : ({tintColor}) =>(
<Icon name="home" color={tintColor}/>
)
}
},
One: {
screen:ScreenOne,
navigationOptions: {
drawerLabel: 'One'
}
},
Two: {
screen:ScreenTwo,
navigationOptions: {
drawerLabel: 'Two'
}
},
Three: {
screen:ScreenThree,
navigationOptions: {
drawerLabel: 'Three'
}
},{
initialRouteName: 'HomePage',
unmountInactiveRoutes : true,
headerMode: 'none'
}
});
Now i need to put a Fixed header and footer for entire app (the drawer must overlay header and footer when is opened),
where header must show an Hamburger menu button inside HomePage, and a BackButton near Hamburger inside the other screen (the footer remain the same all over the app).
How can i do?
You can configure your header with react navigation using navigationOptions property.
Add navigationOptions inside your stack navigator,then all your screens inside the stack navigator should contain a fixed header.
Example:
{
navigationOptions: ({ navigation }) => ({
headerRight: (
<View>
<TouchableOpacity
onPress={() => navigation.openDrawer()}
>
<Image source={hamburgerIcon} style={{ height: 15, width: 15 }} />
</TouchableOpacity>
</View>
),
headerTintColor: 'color',
headerTitle: (
<Text>
title
</Text>
),
headerStyle: {
backgroundColor: '#fff',
},
}),
});
For fixed footer you can use Tab navigation.
Example:
const TabNavigator = createBottomTabNavigator({
Home: { screen: HomeScreen },
Settings: { screen: SettingsScreen },
Gallery: { screen: Gallery}
});
Just add the header and footer in your App.js file or in your NavigationContainer above and below your navigator like in this snack or the following example.
import * as React from 'react';
import { View, Button, Text, Dimensions, StatusBar } from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
function HomeScreen({ navigation }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<Button
title="Go to One"
onPress={() => navigation.navigate('One')}
/>
<Button
title="Go to Two"
onPress={() => navigation.navigate('Two')}
/>
</View>
);
}
function OneScreen({ navigation }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>One Screen</Text>
<Button
title="Go to Home"
onPress={() => navigation.navigate('Home')}
/>
<Button
title="Go to Two"
onPress={() => navigation.navigate('Two')}
/>
</View>
);
}
function TwoScreen({ navigation }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Two Screen</Text>
<Button
title="Go to One"
onPress={() => navigation.navigate('One')}
/>
<Button
title="Go to Home"
onPress={() => navigation.navigate('Home')}
/>
</View>
);
}
const Stack = createNativeStackNavigator();
function App() {
const width = Dimensions.get('window').width;
return (
<NavigationContainer>
<StatusBar />
<View
style={{
backgroundColor: '#007AFF',
height: 50,
width: width,
justifyContent: 'center',
alignItems: 'center',
marginTop: StatusBar.currentHeight,
}}>
<Text>Header</Text>
</View>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="One" component={OneScreen} />
<Stack.Screen name="Two" component={TwoScreen} />
</Stack.Navigator>
<View
style={{
backgroundColor: '#007AFF',
height: 50,
width: width,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text>Footer</Text>
</View>
</NavigationContainer>
);
}
export default App;

React-Native - Rendering Component on Button click using JSON data

I am completely new to React Native. So please apologize me for very naive questions.
I have a main screen which has a button. When the button is pressed I want to fetch data thru another component and display on the screen.
I have App.js
import React from 'react';
import { Button, View, Text } from 'react-native';
import { createAppContainer, createStackNavigator } from 'react-navigation'; // Version can be specified in package.json
import {getMovies} from "./fetchmenu.js";
class HomeScreen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<View style={{ flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'center' }}>
<Button
title="Menu"
onPress={() => {
<getMovies /> // I want to display data as a result of button press
}}
/>
</View>
</View>
);
}
}
const AppContainer = createAppContainer(RootStack);
export default class App extends React.Component {
render() {
return <AppContainer />;
}
}
And fetchmenu.js
import React from 'react';
import { FlatList, ActivityIndicator, Text, View } from 'react-native';
export default class getMovies extends React.Component {
constructor(props){
super(props);
this.state ={ isLoading: true}
}
componentDidMount(){
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson.movies,
}, function(){
});
})
.catch((error) =>{
console.error(error);
});
}
render(){
if(this.state.isLoading){
return(
<View style={{flex: 1, padding: 20}}>
<ActivityIndicator/>
</View>
)
}
return(
<View style={{flex: 1, paddingTop:20}}>
<FlatList
data={this.state.dataSource}
renderItem={({item}) => <Text>{item.title}, {item.releaseYear}</Text>}
keyExtractor={({id}, index) => id}
/>
</View>
);
}
}
How do I display the FlatList created by getMovies on HomeScreen
when the button is pressed?
In your HomeScreen set your state like this:
state={showMovies:false}
Then on Button click setState to {showMovies:true}. And in your render function in App.js:
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<View style={{ flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'center' }}>
<Button
title="Menu"
onPress={() => {
this.setState({showMovies:true});
}}
/>
{this.state.showMovies&&<GetMovies/>}
</View>
</View>
);
}
Since you are exporting getMovies class as default export (not named) do the same with importing:
WRONG: import {getMovies} from "./fetchmenu.js";
CORRECT: import GetMovies from "./fetchmenu.js";
I strongly recommend you to watch some tutorials before getting into real projects.
EDIT
As #Milore stated Component names in React must start with capital letter. See this for further information
constructor(props){
super(props);
this.state ={ isLoading: true}
}
I don't see dataSource in this.state but you are using
this.setState({
isLoading: false,
dataSource: responseJson.movies,
}, function(){
});

Error when back screen from navigation header : undefined is not an object (evaluating 'this.props.navigation.navigate')

I am new in react native. I am trying to close screen on button click in static navigationOptions but getting error like this
My code is here:
import React from 'react';
import { Button, View, Text ,Image } from 'react-native';
import { createStackNavigator } from 'react-navigation'; // Version can be specified in package.json
import Mylistview from './Mylistview.js'
import { TouchableOpacity } from 'react-native'
class HomeScreen extends React.Component {
static navigationOptions = {
header: null ,
};
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<Button
title="Go to Details"
onPress={() => this.props.navigation.navigate('Details')}
/>
</View>
);
}
}
class BackClass extends React.Component {
}
class DetailsScreen extends React.Component {
static navigationOptions = {
headerLeft: //<BackClass />,
<Button
title="Go back"
onPress={() =>this.props.navigation.goBack(null)} //problem is here
/>,
headerTitle: (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', flexDirection: 'row'
, justifyContent: 'space-between' , backgroundColor: 'black'}}>
<Button
style={{ width: 130, height: 30,flex: 1, alignItems: "center", justifyContent: 'center'}}
onPress={() => alert('This is a button!')}
title="Info change"
color="#fff000"
/>
<Button
style={{ height: 30, alignItems: "center", justifyContent: 'center'}}
onPress={() => alert('This is a button!')}
title="second"
color="#fff000"
/>
</View>
),
// headerStyle: {
// elevation: 0,
// shadowOpacity: 0
// }
headerStyle: {
height: 50,
backgroundColor: 'green',
shadowColor: 'red',
shadowRadius: 5,
shadowOpacity: 0.1,
shadowOffset: {
height: 1,
width: 0,
},
},
// titleStyle: { color: 'red' },
// left: <Text style={{color: 'red'}} onPress={() => navigation.goBack()}>LEFT</Text>,
// right: <Text style={{color: 'red'}} onPress={() => navigation.goBack()}>RIGHT</Text>,
};
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Details Screen</Text>
<Button
title="Go to Details... again once"
onPress={() => this.props.navigation.push('Details')}
/>
<Button
title="Go to List"
onPress={() => this.props.navigation.push('List1')}
/>
<Button
title="Go back"
onPress={() => this.props.navigation.goBack()}
/>
</View>
);
}
}
class ListScreen extends React.Component {
render() {
return (
<Mylistview />
)
}
}
const RootStack = createStackNavigator(
{
Home: {
screen: HomeScreen,
// navigationOptions: {
// title: 'screenA',
// }
// navigationOptions: {
// header: {
// visible: false
// }
// }
},
Details: {
screen: DetailsScreen,
},
List1: {
screen: ListScreen,
},
},
{
initialRouteName: 'Home',
}
);
export default class App extends React.Component {
render() {
return <RootStack />;
}
}
//"react-navigation": "^1.0.0-beta.7"
If you want to use the navigate function from within a navigation header component you need to do it like so
static navigationOptions = ({navigation}) => ({
headerRight: <Button
title="Go back"
onPress={() => navigation.goBack()}
/>,
})