How to navigate to another screen from a Redux form with React navigation? - react-native

Basically I want that within a props.handleSubmit function you can navigate to another screen.
Here is my code :
import React, { Component } from "react";
import { createStackNavigator, createAppContainer } from 'react-navigation';
import { Provider } from 'react-redux';
import Store from './Store/Store'
import ScreenSignUp from './Navigation/ScreenSignUp';
import ScreenSignIn from './Navigation/ScreenSignIn';
import ScreenHome from "./Navigation/ScreenHome";
class App extends Component {
render() {
return (
<Provider store={Store}>
<AppContainer />
</Provider>
);
}
}
export default App;
const RootStack = createStackNavigator(
{
Home: ScreenHome,
SignUp: ScreenSignUp,
SignIn: ScreenSignIn,
},
{
initialRouteName: 'SignIn',
defaultNavigationOptions: {
header: null,
},
},
);
const AppContainer = createAppContainer(RootStack);

you can do it like this
export default reduxForm({
form: 'SignInForm',
onSubmitSuccess : (result, dispatch, props) => {
props.navigation.navigate('Register');
},
onSubmitFail : () => {
Toast.show({
text: "Enter Passport Number",
duration: 2500,
position: "top",
textStyle: { textAlign: "center" }
});
}
validate,
})(SignInForm);

Related

How to write unit test cases for navigation stack in react native using enzyme jest?

I am new to react native and trying to write unit test cases. I am able to write snapshot test cases but not sure how to write unit test cases for navigation stack.
is there any way to write unit test cases for navigation?
navigator.js
import { createStackNavigator } from 'react-navigation-stack';
import { createAppContainer } from 'react-navigation';
import HomeScreen from '../component/HomeComponent/home';
import ThumbnailView from '../component/ThumbnailComponent/thumbnailView';
import AlbumDetailsView from '../component/AlbumDetailsComponent/albumDetailsView';
const MainNavigator = createStackNavigator({
HomeScreen: { screen: HomeScreen },
ThumbnailViewScreen: { screen: ThumbnailView },
AlbumDetailsViewScreen: { screen: AlbumDetailsView },
},
{
defaultNavigationOptions: {
headerTintColor: '#fff',
headerStyle: {
backgroundColor: '#0c82f3',
},
headerTitleStyle: {
fontWeight: 'bold',
},
},
});
const NavigationApp = createAppContainer(MainNavigator);
export default NavigationApp;
You can test navigate function in your components like this:
import HomeScreen from '../component/HomeComponent/home';
import { shallow, ShallowWrapper } from "enzyme";
import React from "react";
import { View } from "react-native";
const createTestProps = (props) => ({
navigation: {
navigate: jest.fn()
},
...props
});
describe("HomeScreen", () => {
describe("rendering", () => {
let wrapper;
let props;
beforeEach(() => {
props = createTestProps({});
wrapper = shallow(<HomeScreen {...props} />);
});
it("should render a <View /> and go to ThumbnailViewScreen", () => {
expect(wrapper.find(View)).toHaveLength(1); // Some other tests
expect(props.navigation.navigate).toHaveBeenCalledWith('ThumbnailViewScreen'); // What you want
});
});
});
HomeScreen.js :
import React, { Component } from "react";
import { Text, View } from "react-native";
export class HomeScreen extends Component {
componentDidMount = () => {
this.props.navigation.navigate("ThumbnailViewScreen");
};
render() {
return (
<View>
<Text>This is the HomeScreen.</Text>
</View>
);
}
}
export default HomeScreen;
You can find more details here

Can't open Drawer react native

I created createDrawerNavigator. But when call "props.navigation.dispatch(DrawerActions.openDrawer())" nothing show. Here is my code.
MenuNavigator.js
import { createDrawerNavigator } from "react-navigation";
import Login from "../screens/auth/Login"
import ForgotPassword from "../screens/auth/ForgotPassword"
import SignUp from "../screens/auth/SignUp";
const MenuNavigator = createDrawerNavigator({
//Drawer Optons and indexing
ForgotPassword: ForgotPassword,
SignUp: SignUp,
},
{
contentOptions: {
activeTintColor: '#e91e63',
},
}
);
export default MenuNavigator;
AppNavigator
import { createStackNavigator, createAppContainer } from "react-navigation";
import StackNavigatorMain from "./StackNavigatorMain"
import MenuNavigator from "./MenuNavigator"
const AppNavigator = createStackNavigator(
{
StackNavigatorMain: StackNavigatorMain,
MenuNavigator: MenuNavigator
},
{
headerMode: "none",
navigationOptions: {
headerVisible: false
},
initialRouteName: "StackNavigatorMain"
}
);
export default createAppContainer(AppNavigator);
Call openDrawer
onLoginClicked = () => {
props.navigation.dispatch(DrawerActions.openDrawer());
}
First get the reference of the navigator from top level component like this:
const AppContainer = createAppContainer(AppNavigator);
return <AppContainer ref={navigatorRef => Navigation.setTopLevelNavigator(navigatorRef)} />;
In Navigation.js file you need to set a global variable for navigator reference :
let _navigator;
function setTopLevelNavigator(navigatorRef) {
_navigator = navigatorRef;
}
Then create function there like this:
function openDrawer() {
_navigator.dispatch(DrawerActions.openDrawer())
}
Do not forget to import them:
import { DrawerActions } from 'react-navigation';
After that export them from Navigation.js file:
export default {
setTopLevelNavigator,
openDrawer,
}
AFAIK Opening drawer from React-navigation v3 is called like this piece of code
this.props.navigation.openDrawer();
EDIT:
I tried to minimally replicate this using react-navigation v3
https://snack.expo.io/#keysl183/basic-drawer-v3

React Native Navigation Root issue with multiple views

Hello All I am facing an issue.
I am trying to set different root in app.js file but it always open Home View. Can anyone tell me what is wrong with my code. Any help would be highly appreciable!
import React, { Component } from "react";
import { View, Text, AsyncStorage, AppRegistry } from "react-native";
import LoginContainer from "./Login/LoginContainer";
import { createStackNavigator, createAppContainer } from "react-navigation";
import Home from "./Dashboard/Home";
const RootStack = createStackNavigator(
{
login: { screen: LoginContainer },
Home: { screen: Home }
},
{
initialRouteName: "login"
}
);
const AppContainer = createAppContainer(RootStack);
class Demo extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
email: ""
};
}
componentDidMount() {
const email = AsyncStorage.getItem("email").then(email => {
this.setState({
isLoading: false,
email: email
});
});
}
render() {
if (this.state.isLoading) {
return (
<View>
<Text>Loading..</Text>
</View>
);
}
if (this.props.email !== "") {
return <Home />;
} else {
return <AppContainer />;
}
}
}
export default Demo;
AppRegistry.registerComponent("Demo", () => Demo);
Instead of
export default Demo;
Use this :
export default AppContainer;
or
export default createAppContainer(RootStack);

react native updating redux store from app.js not working

https://snack.expo.io/#mparvez19861/redux-example
I have below code in app.js in
import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View } from 'react-native';
import Geolocation from 'react-native-geolocation-service';
import firebase from './FireBaseSetup/Firebase'
// import DrawerNavigatorExample from './Navigations';
import Navigator from './Navigator'
import Permissions from 'react-native-permissions'
import { PermissionsAndroid } from 'react-native';
import PermissionsList from './Utitliy/PermissionsList'
import Contacts from 'react-native-contacts';
import { Provider, connect } from 'react-redux';
import { store, persistor, setCurrentLocation } from './redux/app-redux';
import { PersistGate } from 'redux-persist/integration/react'
import SplashScreen from './screens/SplashScreen'
const mapDispatchToProps = (dispatch) => {
return {
setCurrentLocation: (location) => { dispatch(setCurrentLocation(location)) }
};
}
const ConnectedApp = connect(mapDispatchToProps)(Navigator);
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
latitude: null,
longitude: null,
error: null,
};
}
async componentDidMount() {
this.getContacts();
await new PermissionsList().requestLocationPermission();
Geolocation.getCurrentPosition(
(position) => {
// this.setState({
// latitude: position.coords.latitude,
// longitude: position.coords.longitude,
// error: null,
// });
this.props.setCurrentLocation(position);
firebase.firestore().collection('locations').doc('8686').set({
locations: position
})
},
(error) => alert(JSON.stringify(error)),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000, distanceFilter: 100 }
);
this.watchId = Geolocation.watchPosition(
(position) => {
// this.setState({
// latitude: position.coords.latitude,
// longitude: position.coords.longitude,
// error: null,
// });
this.props.setCurrentLocation(position);
firebase.firestore().collection('locations').doc('8686').set({
locations: position
})
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: false, timeout: 20000, maximumAge: 10000, distanceFilter: 1 },
);
}
componentWillUnmount() {
Geolocation.clearWatch(this.watchId);
}
render() {
return (
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<View style={styles.container}>
<ConnectedApp />
</View>
</PersistGate>
</Provider>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
});
Navigator.js
import React, { Component } from 'react';
import { View, Text, TouchableHighlight, Image } from 'react-native';
import { createDrawerNavigator, createStackNavigator , createSwitchNavigator, createAppContainer } from 'react-navigation';
import {
ActivityIndicator,
AsyncStorage,
Button,
StatusBar,
StyleSheet
} from 'react-native';
// import firebase from 'react-native-firebase';
// import { store } from '../redux/app-redux';
import Screen2 from './screens/Screen2';
import SplashScreen from './screens/SplashScreen'
import Login from './screens/Login'
import SignOutScreen from './screens/SignOutScreen'
import screendesign from './screens/screendesign'
import EmailPwdLogin from './screens/EmailPwdLogin'
import friends from './screens/friends'
import LoginScreen from './screens/LoginScreen';
import SignupScreen from './screens/SignupScreen';
const AuthStack = createStackNavigator({
// { SignIn: SignInScreen }
// SignIn: { screen: EmailPwdLogin }
Login: { screen: Login },
Signup: { screen: SignupScreen },
});
const drNav = createDrawerNavigator(
{
friends: {
screen: friends
},
Screen2: {
screen: Screen2
},
SignOut: {
screen: SignOutScreen
}
}
)
export default createAppContainer(createSwitchNavigator(
{
// screendesign: screendesign,
SplashScreen: SplashScreen,
App: drNav,
AuthStack: AuthStack
},
{
initialRouteName: 'SplashScreen',
}
));
Redux file
const setCurrentLocation = (location) => {
alert(JSON.stringify(location))
return {
type: "setCurrentLocation",
value: location
};
};
export { setCurrentLocation };
But this setCurrentLocation is not being fired from app.js
please help.
Thanks
You are trying to dispatch a redux action from App.js which is the entry point of your application and where you initialise your redux store. You can use this.props.setCurrentLocation(position) from any connected component within the Provider component, but App.js is outside of it.
So you need to call it like so:
store.dispatch(setCurrentLocation(position))
I tried to run your snack to see if you have any other issues but it throws an error.
Hope this helps
You forget to connect mapDispatchToProps:
export default connect(mapStateToProps,mapDispatchToProps)(App);

How to wrap redux store to my App.js in react native

import React from 'react';
import { View, Text } from 'react-native';
import { StackNavigator } from 'react-navigation';
import HomeScreen from './Home.js';
import EntryPoint from './src/containers/EntryPoint.js';
import Stage2 from './src/containers/Stage2.js';
const RootNavigator = StackNavigator({
Home: {
screen: HomeScreen,
navigationOptions: {
headerTitle: 'Material Management',
},
},
EntryPoint: {
screen: EntryPoint,
navigationOptions: {
headerTitle: 'Entry Point'
}
},
Stage2 : {
screen : Stage2,
navigationOptions : {
headerTitle : 'Stage 2'
}
}
});
export default RootNavigator;
The above code is my App.js
I want to wrap the redux store around it. How do i do that . Couldn't find a proper documentation for redux setup with React-native.
import { createStore,bindActionCreators } from 'redux'
import { connect, Provider } from 'react-redux'
function mapStateToProps(state) {
return state;
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(Actions, dispatch);
}
let Container = connect(mapStateToProps,mapDispatchToProps)(RootNavigator);
export default class APP extends Component{
render(){
return (<Provider store={store}>
<Container/>
</Provider>)
}
};