React navigation does not respond click button - react-native

I'm creating an app with react native and using lib react navigation. When trying to make a button call a new screen, navigation doesn't respond to the click, does anyone know what it might be?
App.js
import Initial from "./app/screens/Initial";
import Login from "./app/screens/Login";
const AppNavigator = createStackNavigator(
{
Initial:{
screen: Initial
},
Login:{
screen: Login
}
},
{
initialRouteName: 'Initial',
headerMode: 'none',
}
);
export default createAppContainer(AppNavigator);
Initial.js (My Screen)
This is the screen where I render the button and call the click event to react with react navigation
import React, { Component } from "react";
import { View, StyleSheet, Text, ImageBackground } from "react-native";
import Button from "../components/Form/Button";
import imageLogo from "../assets/images/background2.jpg";
import colors from "../config/color";
class Initial extends Component {
render(){
const { navigate } = this.props.navigation;
return (
<View style={styles.wrapper}>
<ImageBackground source={imageLogo} style={styles.image}>
<Text style={styles.appName}>Hello</Text>
<View style={styles.areaMarketing}>
<Text style={styles.textAds}>text text text </Text>
<Text style={styles.textAds}>good good good.</Text>
</View>
<View style={styles.form}>
<Button onPress={() => this.props.navigation.navigate('Login')}
buttonBackColor={colors.emerald}
buttonBorderColor={colors.emerald}
color={colors.white} labelButton="Entrar"/>
<Button labelButton="Criar conta"/>
</View>
</ImageBackground>
</View>
);
}
}
const styles = StyleSheet.create({
wrapper: {
flex: 1,
justifyContent: "space-between"
},
form: {
flex: 1,
justifyContent: "flex-end"
},
appName: {
margin: 20,
fontSize: 25,
fontFamily: "Nunito-Bold",
color: colors.white
},
areaMarketing: {
marginLeft: 20
},
textAds: {
color: colors.white,
fontSize: 23,
fontFamily: "Nunito-Regular"
},
image: {
width: "100%",
height: "100%"
}
});
export default Initial;
package.json
"dependencies": {
"react": "16.8.6",
"react-native": "0.60.4",
"react-native-gesture-handler": "^1.3.0",
"react-navigation": "^3.11.1",
"react-navigation-stack": "^1.9.4"

Please look at react navigation 3 simple live example with single one file App.js with 2 screens:
https://snack.expo.io/r1eXFk7tB
P.S.
You didn't provide the full code of your issue like click hanlders and render of buttons but i guess you can see the example to find the problem in your project.

Related

How can I get button-click-navigation and touch-slide-navigation at the same time in React Native?

This is some part of the YouTube video.(using createStackNavigator in React Native).
How can I achieve this kind of effect in React Native( Navigation by button click and touch slide at the same time ) ?
I followed this video but it works such as fadeIn, fadeOut effect in jQuery.
The author of this video installed "yarn add react-navigation#2.0.0-beta.3".
I installed it but it gave me error. So I used this. "yarn add react-navigation".
This is the whole code of App.js.
import React from 'react';
import { Button, View, Text } from 'react-native';
import { createAppContainer } from "react-navigation";
import { createStackNavigator } from 'react-navigation-stack';
class ScreenComponentOne extends React.Component {
render() {
return (
<View
style={{
flex: 1,
alignItems: "center",
justifyContent: "center",
borderWidth: 25,
borderColor: '#f00',
}}
>
<Button
title="Go to the screen two"
onPress={() => {
this.props.navigation.navigate('RouteNameTwo')
}}
/>
</View>
)
}
}
class ScreenComponentTwo extends React.Component {
render() {
return (
<View
style={{
flex: 1,
alignItems: "center",
justifyContent: "center",
borderWidth: 25,
borderColor: '#f0f',
}}
>
<Button
title="Go to the screen one"
onPress={() => {
this.props.navigation.navigate({routeName:'RouteNameOne', transitionStyle: 'inverted'})
}}
/>
</View>
)
}
}
const AppNavigator = createStackNavigator({
RouteNameOne: {
screen:ScreenComponentOne,
navigationOptions:{
header:null,
}
},
RouteNameTwo: {
screen:ScreenComponentTwo,
navigationOptions:{
header:null,
}
},
},
{
initialRouteName:"RouteNameOne"
});
const AppContainer = createAppContainer(AppNavigator);
export default class App extends React.Component {
render() {
return <AppContainer />;
}
}
I'd like to get touch-slide-navigation and button-click-navigation at the same time.
The module that I installed is as follows:
-yarn install
-yarn add react-navigation (for createAppContainer)
-yarn add react-navigation-stack (for createStackNavigator)
How can I achieve this ?

How do i navigate between screens in my shopping app?

'm new to react-native and mobile application. I'm trying to build a basic shopping app.i have the sports options such as cricket,football,tennis and whenever the cricket button is pressed, the cricket products must be displayed and i can follow it up for the other two products
i tried using stack navigator to navigate between screens but i seem to get a error . i tried using createstacknavigator but it doesnt come out right
1.App.js
import React, { Component } from 'react';
import { Text, View } from 'react-native';
import { StackNavigator } from 'react-navigation'
import FirstScreen from './src/FirstScreen'
import SecondScreen from './src/cricket'
const Navigation = StackNavigator({
First: {screen: FirstScreen},
Second: {screen: SecondScreen}
});
export default Navigation
AppRegistry.registerComponent('AwesomeProject', () => Navigation);
2.FirstScreen.js
import React, { Component } from 'react';
import { Alert, AppRegistry, Image, Platform, StyleSheet, Text,
TouchableHighlight, TouchableOpacity, TouchableNativeFeedback,
TouchableWithoutFeedback, View } from 'react-native';
import { StackNavigator } from 'react-navigation'
export default class FirstScreen extends Component {
//_onPressButton() {
// Alert.alert('You tapped the button!')
//}
//_onLongPressButton() {
//Alert.alert('You long-pressed the button!')
//}
static navigationOptions = {
title: 'First Screen',
};
render() {
return (
<View style={styles.container}>
<TouchableOpacity onPress={this._onPressButton}>
<View style={styles.button}>
<Text style={styles.buttonText}>Cricket</Text>
</View>
</TouchableOpacity>
<TouchableOpacity onPress={this._onPressButton}>
<View style={styles.button}>
<Text style={styles.buttonText}>Football</Text>
</View>
</TouchableOpacity>
<TouchableOpacity onPress={this._onPressButton}>
<View style={styles.button}>
<Text style={styles.buttonText}>Tennis</Text>
</View>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
paddingTop: 60,
alignItems: 'center'
},
button: {
marginBottom: 30,
width: 260,
alignItems: 'center',
backgroundColor: '#2196F3'
},
buttonText: {
padding: 20,
color: 'white'
}
});
// skip this line if using Create React Native App
//AppRegistry.registerComponent('AwesomeProject', () => Touchables);
3.Cricket.js
import React, { Component } from 'react';
import {Alert, Button, ScrollView, StyleSheet, AppRegistry, Text, View
} from 'react-native';
const styles = StyleSheet.create({
rowContainer: {
flex: 1,
height: 75,
width: '100%',
flexDirection: 'row', // children will be on the same line
justifyContent: 'space-between',
alignItems: 'center',
margin: 10,
},
buttonContainer: {
flex: 1,
},
text: {
flex: 2, // Text takes twice more space as button container
color: 'red',
fontWeight: 'bold',
fontSize: 20,
},
});
class Greeting extends Component {
static navigationOptions = {
title: 'Second Screen',
};
_onPressButton() {
Alert.alert('Sorry you have no credit!')
}
render() {
return (
<View style={styles.rowContainer}>
<Text style={styles.text}>{this.props.name}</Text>
<View style={styles.buttonContainer}>
<Button
onPress={this._onPressButton}
title="BUY"
/>
</View>
</View>
);
}
}
export default class SecondScreen extends Component {
render() {
return (
<ScrollView>
<View style={{alignItems: 'flex-start', top: 0, flex: 2,
backgroundColor: 'black'}}>
<Greeting name='Shoe- 800' />
<Greeting name='Jersey - 350' />
<Greeting name='Stockings - 100' />
<Greeting name='Cones - 50' />
<Greeting name='Whistle - 80' />
<Greeting name='Helmet - 750' />
<Greeting name='Tennis Ball-6 pack - 800' />
<Greeting name='Nets - 1500' />
<Greeting name='Leg Pads - 1000' />
<Greeting name='Stumps - 800' />
<Greeting name='Gloves - 600' />
</View>
</ScrollView>
);
}
}
When the cricket button is pressed, the screen should navigate to the list of cricketproducts which is the (cricket.js)
As you are using react-navigation, you just need to use the navigation prop. You have commented the part where you handle the press. Just change that function to actually navigate to the screen you want:
_onPressButton=()=>{
this.props.navigation.navigate("Second")
}
If you are not using arrow functions, you need to bind the function to have access to the this of that screen. To do that you need to add inside your constructor:
constructor(props){
super(props)
this._onPressButton.bind(this)
}
after that you can call it by doing:
_onPressButton() {
this.props.navigation.navigate("Second")
}
As you are using a stackNavigator, you have different ways to navigate to the other screen of the same stack. You have different ways to navigate. For example:
this.props.navigation.push("Second")
This method pushes a new screen to the stack, no matter what screen it is
this.props.navigation.navigate("Second")
Navigates to a new screen in the stack, will push it in the stack only if the screen hasn't been focussed before
this.props.navigation.replace("Second")
This will navigate to a new screen without pushing it to the stack, "replacing" the screen you was watching with the new one.
EDIT.
For the error you stated in the comment, it's because there's not an app container. To do so, just do:
import { createStackNavigator, createAppContainer } from 'react-navigation'
Then do
const Navigation = createAppContainer(createStackNavigator({
First: {screen: FirstScreen},
Second: {screen: SecondScreen}
}));
Use the Move Screen command.
this.props.navigation.navigate("Second")

Custom navigator menu in React Native

I'm new in React Native and have a project with a kind of menu on the right side (5 buttons) on several screens. What I want to do is to use this menu only once for the whole app with a container, and change the content of the container according to the selected button, like in Android with fragment and fragmentManager.replace...
Screens and menu are developed but I really don't know how to mix everything properly .
I read doc about react-navigation (https://reactnavigation.org/docs/en/custom-navigators.html) but do not understand well everything. However I just need a kind of TabNavigator with custom Tab on the ride side.
Please help me.
Not sure what do you mean, but i think you could try something like this:
const CustomDrawer = createDrawerNavigator({
Screen1: {
screen: Screen1,
},
Screen2: {
screen: Screen2,
},
})
const RootNavigator = createStackNavigator({
MainScreen: {
screen: MainScreen,
},
CustomDrawer: { screen: CustomDrawer }
},
{
initialRouteName: 'Init',
})
Basically, you can create a Drawer on the right/left. And add your 5 screens on it, then you will use the drawer to navigate between those screens. Plus you'll instantiate your drawer on a stackNavigator which will handle the navigation. You can also set your main screen on it and everything else.
I think you want drawer in react native app using react-navigation..
use createDrawerNavigator it providers you to custom design your side bar
createDrawerNavigator({
screen: {..your screen stack here...}
}, {
headerMode: 'none',
gesturesEnabled: false,
contentComponent: DrawerContainer, /// DrawerContainer is custom component container for all tabs
drawerBackgroundColor: 'transparent',
drawerWidth: 240,
useNativeAnimations: true
});
DrawerContainer .js :---
export default class DrawerContainer extends React.Component {
render() {
return (
<View style={{flex:1}}>
<TouchableOpacity
style={{borderBottomColor: '#fff', height: 40}}
onPress={() => this.props.navigation.navigate('screen name')}
>
<Text style={{color: '#FFFFFF',fontSize: 18}}
type='h5White'>your tab name</Text>
</TouchableOpacity>
</View>
);
}
}
for more detail go to https://medium.freecodecamp.org/how-to-build-a-nested-drawer-menu-with-react-native-a1c2fdcab6c9
go for this medium tutorial
https://medium.com/#mehulmistri/drawer-navigation-with-custom-side-menu-react-native-fbd5680060ba
create custom side bar always fixed:---
Don't use drawer. I m making it by using hoc (Higher-Order Components)
Fist make Higher-Order Components as sidebar.js
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
TouchableOpacity
} from 'react-native';
const withSidebar = WrappedComponent => class extends Component {
constructor(props) {
super(props);
this.state = { isConnected: true };
}
render() {
return (
<View style={styles.container}>
<View style={{width:50, top:20, backgroundColor: 'grey',}}>
<TouchableOpacity
style={styles.menu}
onPress={() => console.log('code')}
>
<Text style={styles.menuText} type='h5White'>first</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.menu}
onPress={() => console.log('code')}
>
<Text style={styles.menuText} type='h5White'>second</Text>
</TouchableOpacity>
</View>
<View style={{flex:1, backgroundColor: 'red', top:20}}>
<WrappedComponent {...this.props} />
</View>
</View>
);
}
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
flexDirection: 'row',
},
welcome: {
flex: 1,
margin: 20,
backgroundColor: 'orange',
margin: 10,
textAlign: 'center',
fontSize: 20,
paddingTop: 70,
},
menu: {
paddingHorizontal: 7,
borderBottomWidth: 1,
borderBottomColor: '#fff',
height: 40,
justifyContent: 'center'
},
menuText: {
justifyContent: 'center',
color: '#FFFFFF',
fontSize: 10,
fontWeight: 'bold'
},
});
export default withSidebar;
Now only connect your screen with this hoc:--
import sidebar.js in your screen as
import withSidebar from 'sidebar'
export default connect(mapStateToProps, mapDispatchToProps)(withSidebar(yourScreenName));
This HOC is available for every screen where you want just use above syntax.
You can also put it in your root level component only once to get it for whole components (its over you how you implement this).

React Native render and switch with navigator onPress

I've just started to develop with React Native a week ago.
Can anyone help me with simple render and switch onPress to another view?
I've read tones of examples, but most of them are cutted or not well documents as if on FaceBook Doc pages. There was no totally completed example with Nav.
Here is what was done yet - View that should be rendered 1st:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Image,
TextInput,
TouchableHighlight,
TouchableNativeFeedback,
Platform,
Navigator
} from 'react-native';
export default class SignUp extends Component {
buttonClicked() {
console.log('Hi');
this.props.navigator.push({title: 'SignUp', component:SignUp});
}
render() {
var TouchableElement = TouchableHighlight;
if (Platform.OS === ANDROID_PLATFORM) {
TouchableElement = TouchableNativeFeedback;
}
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to Cross-Profi!
</Text>
<Text style={styles.field_row}>
<TextInput style={styles.stdfield} placeholder="Profession" />
</Text>
<Text style={styles.field_row}>
<TextInput style={styles.stdfield} placeholder="E-mail" />
</Text>
<Text style={styles.field_row}>
<TextInput style={styles.stdfield} secureTextEntry={true} placeholder="Password" />
</Text>
<TouchableElement style={styles.button} onPress={this.buttonClicked.bind(this)}>
<View>
<Text style={styles.buttonText}>Register</Text>
</View>
</TouchableElement>
{/* <Image source={require("./img/super_car.png")} style={{width:120,height:100}} />*/}
<Text style={styles.instructions}>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'lightblue',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
color: 'darkred',
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
field_row: {
textAlign: 'center',
color: '#999999',
margin: 3,
},
stdfield: {
backgroundColor: 'darkgray',
height: 50,
width: 220,
textAlign: 'center'
},
button: {
borderColor:'blue',
borderWidth: 2,
margin: 5
},
buttonText: {
fontSize: 18,
fontWeight: 'bold'
}
});
const ANDROID_PLATFORM = 'android';
Navigator class that should render different views:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Platform,
Navigator
} from 'react-native';
var MainActivity = require('./app/MainActivity.js');
var SignUp = require('./app/SignUp.js');
class AwesomeProject extends Component {
/*constructor(props) {
super(props);
this.state = {text: ''};
}*/
render() {
// this.props.navigator.push({title:'SignUp'});
return (
<Navigator initialRoute={{title:'SignUp', component:SignUp}}
configureScene={() => {
return Navigator.SceneConfigs.FloatFromRight;
}}
renderScene={(route, navigator) =>
{
console.log(route, navigator);
if (route.component) {
return React.createElement(route.component, {navigator});
}
}
} />
);
}
}
const ANDROID_PLATFORM = 'android';
const routes = [
{title: 'MainActivity', component: MainActivity},
{title: 'SignUp', component: SignUp},
];
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
It doesn't seem to be clear whether there must be require of a class and declaration of class as export default.
There is an error: Element type is invalid: expected a string, ... but got object etc
Help with examples would be great. Thx
In your require call, you should either replace it import statement or use default property of require module i.e:
var MainActivity = require('./app/MainActivity.js').default;
or use
import MainActivity from "./app/MainActivity";
In ES6, require doesn't assign default property of module to variable.
See this blog post for better understanding of require working in es6

How can I change the text in TabBarIOS in React Native?

In the react native documentation I cannot find a way to change the bottom words?
<TabBarItemIOS
name="greenTab"
icon={_ix_DEPRECATED('more')}
accessibilityLabel="Green Tab"
selected={this.state.selectedTab === 'greenTab'}
onPress={() => {
this.setState({
selectedTab: 'greenTab',
presses: this.state.presses + 1
});
}}>
{this._renderContent('#21551C', 'Green Tab')}
</TabBarItemIOS>
What is the accessibilityLabel ?
The TabBarItem allows you to use one of the iOS preset icons from UITabBarSystemItem, and in your sample code it's using the "More" icon. Crucially though, the documentation for UITabBarSystemItem states:
The title and image of system tab bar items cannot be changed.
If you set the icon to either a data-uri or a local image, rather than an icon from UITabBarSystemItem, you'll be able to override the text on the item to whatever you want using the title prop.
You can try something like that for your TabBarIOS.Item with a custom icon
import React, { Component } from 'react'
import { AppRegistry, StyleSheet, Text, View, TouchableOpacity, TabBarIOS } from 'react-native'
const base64Icon = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEsAAABLCAQAAACSR7JhAAADtUlEQVR4Ac3YA2Bj6QLH0XPT1Fzbtm29tW3btm3bfLZtv7e2ObZnms7d8Uw098tuetPzrxv8wiISrtVudrG2JXQZ4VOv+qUfmqCGGl1mqLhoA52oZlb0mrjsnhKpgeUNEs91Z0pd1kvihA3ULGVHiQO2narKSHKkEMulm9VgUyE60s1aWoMQUbpZOWE+kaqs4eLEjdIlZTcFZB0ndc1+lhB1lZrIuk5P2aib1NBpZaL+JaOGIt0ls47SKzLC7CqrlGF6RZ09HGoNy1lYl2aRSWL5GuzqWU1KafRdoRp0iOQEiDzgZPnG6DbldcomadViflnl/cL93tOoVbsOLVM2jylvdWjXolWX1hmfZbGR/wjypDjFLSZIRov09BgYmtUqPQPlQrPapecLgTIy0jMgPKtTeob2zWtrGH3xvjUkPCtNg/tm1rjwrMa+mdUkPd3hWbH0jArPGiU9ufCsNNWFZ40wpwn+62/66R2RUtoso1OB34tnLOcy7YB1fUdc9e0q3yru8PGM773vXsuZ5YIZX+5xmHwHGVvlrGPN6ZSiP1smOsMMde40wKv2VmwPPVXNut4sVpUreZiLBHi0qln/VQeI/LTMYXpsJtFiclUN+5HVZazim+Ky+7sAvxWnvjXrJFneVtLWLyPJu9K3cXLWeOlbMTlrIelbMDlrLenrjEQOtIF+fuI9xRp9ZBFp6+b6WT8RrxEpdK64BuvHgDk+vUy+b5hYk6zfyfs051gRoNO1usU12WWRWL73/MMEy9pMi9qIrR4ZpV16Rrvduxazmy1FSvuFXRkqTnE7m2kdb5U8xGjLw/spRr1uTov4uOgQE+0N/DvFrG/Jt7i/FzwxbA9kDanhf2w+t4V97G8lrT7wc08aA2QNUkuTfW/KimT01wdlfK4yEw030VfT0RtZbzjeMprNq8m8tnSTASrTLti64oBNdpmMQm0eEwvfPwRbUBywG5TzjPCsdwk3IeAXjQblLCoXnDVeoAz6SfJNk5TTzytCNZk/POtTSV40NwOFWzw86wNJRpubpXsn60NJFlHeqlYRbslqZm2jnEZ3qcSKgm0kTli3zZVS7y/iivZTweYXJ26Y+RTbV1zh3hYkgyFGSTKPfRVbRqWWVReaxYeSLarYv1Qqsmh1s95S7G+eEWK0f3jYKTbV6bOwepjfhtafsvUsqrQvrGC8YhmnO9cSCk3yuY984F1vesdHYhWJ5FvASlacshUsajFt2mUM9pqzvKGcyNJW0arTKN1GGGzQlH0tXwLDgQTurS8eIQAAAABJRU5ErkJggg=='
class ReactNativePlayground extends Component {
constructor(props) {
super(props)
this.state = {
selectedTab: "more",
tabBarItemTitle: "More"
}
}
render() {
return (
<TabBarIOS>
<TabBarIOS.Item selected={this.state.selectedTab === "more"}
title={this.state.tabBarItemTitle}
icon={{uri: base64Icon, scale: 3}}>
<View style={styles.container}>
<TouchableOpacity onPress={ (event) => { this._changeTabItemTitle() } }>
<Text style={styles.button}>Tap to Change Item Title</Text>
</TouchableOpacity>
</View>
</TabBarIOS.Item>
</TabBarIOS>
);
}
_changeTabItemTitle() {
this.setState({ tabBarItemTitle: "New More" })
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
},
button: {
fontSize: 20,
color: "white",
textAlign: 'center',
backgroundColor: "#1155DD",
borderRadius: 5,
height: 30,
margin: 30,
},
});
AppRegistry.registerComponent('ReactNativePlayground', () => ReactNativePlayground);