Related
I'm learning react native through a book and I was following the guide step by step. As I was coding and seeing the changes in the app I came across this error and I don't know what it means. I reviewed the code and compared with the code of the book and it's the same. I also searched the internet for some answers and couldn't find any. I'd be really glad if someone could tell me what I'm doing wrong here.
Here's the error I'm getting on the app:
The error in the windows terminal:
TypeError: undefined is not an object (evaluating '_this.submitTodo.bind')
This error is located at:
in App (at TodoApp/index.js:9)
in TodoApp (at renderApplication.js:50)
in RCTView (at View.js:32)
in View (at AppContainer.js:92)
in RCTView (at View.js:32)
in View (at AppContainer.js:119)
in AppContainer (at renderApplication.js:43)
in TodoApp(RootComponent) (at renderApplication.js:60)
Here's the App.js code:
import React, { Component } from 'react'
import { View, ScrollView, StyleSheet } from 'react-native'
import Heading from './Heading'
import Input from './Input'
import Button from './Button'
let todoIndex = 0
class App extends Component {
constructor() {
super()
this.state = {
inputValue: '',
todos: [],
type: 'All'
}
this.submitTodo = this.submitTodo.bind(this)
}
inputChange(inputValue) {
console.log(' Input Value: ' , inputValue)
this.setState({ inputValue })
}
sumbitTodo () {
if (this.state.inputValue.match(/^\s*$/)) {
return
}
const todo = {
title: this.state.inputValue,
todoIndex,
complete: false
}
todoIndex++
const todos = [...this.state.todos, todo]
this.setState({ todos, inputValue: '' }, () => {
console.log('State: ', this.state)
})
}
render () {
const { inputValue } = this.state
return (
<View style={styles.container}>
<ScrollView keyboardShouldPersistTaps='always' style={styles.content}>
<Heading />
<Input
inputValue={inputValue}
inputChange={ (text) => this.inputChange(text) } />
<Button submitTodo={this.submitTodo} />
</ScrollView>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#f5f5f5'
},
content: {
flex: 1,
paddingTop: 60
}
})
export default App
Here's the Button.js code which might help:
import React from 'react'
import { View, Text, StyleSheet, TouchableHighlight } from 'react-native'
const Button = ({ submitTodo }) => (
<View style={styles.buttonContainer}>
<TouchableHighlight
underlayColor='#efefef'
style={styles.button}
onPress={submitTodo}>
<Text style={styles.submit}>
Submit
</Text>
</TouchableHighlight>
</View>
)
const styles = StyleSheet.create({
buttonContainer: {
alignItems: 'flex-end'
},
button: {
height: 50,
paddingLeft: 20,
paddingRight: 20,
backgroundColor: '#ffffff',
width: 200,
marginRight: 20,
marginTop: 15,
borderWidth: 1,
borderColor: 'rgba(0,0,0,.1)',
justifyContent: 'center',
alignItems: 'center'
},
submit: {
color: '#666666',
fontWeight: '600'
}
})
export default Button
Here's the Input.js code which might help as well.
import React from 'react'
import { View, TextInput, StyleSheet } from 'react-native'
const Input = ({ inputValue, inputChange }) => (
<View style={styles.inputContainer}>
<TextInput
value={inputValue}
style={styles.input}
placeholder='What needs to be done?'
placeholderTextColor='#CACACA'
selectionColor='#666666'
onChangeText={inputChange} />
</View>
)
const styles = StyleSheet.create({
inputContainer: {
marginLeft: 20,
marginRight: 20,
shadowOpacity: 0.2,
shadowRadius: 3,
shadowColor: '#000000',
shadowOffset: { width: 2, height: 2 }
},
input: {
height: 60,
backgroundColor: '#ffffff',
paddingLeft: 10,
paddingRight: 10,
}
})
export default Input
I am new to React Native. I want to create a simple counter button. I could not use "this", it gives error ('this' implicitly has type 'any' because it does not have a type annotation.). You can see my TabTwoScreen.tsx TypeScript code below. I searched other questions but i could not find what to do. Why this is not working and how can I correct it. Waiting for helps. Thanks a lot.
import * as React from 'react';
import { StyleSheet, Button, Alert } from 'react-native';
import EditScreenInfo from '../components/EditScreenInfo';
import { Text, View } from '../components/Themed';
export default function TabTwoScreen() {
const state={
counter: 0,
}
const but1 = () => {
this.setState({counter : this.state.counter + 1});
};
return (
<View style={styles.container}>
<Text style={styles.title}>Counter:{state.counter}</Text>
<Button
title="Increment"
onPress={but1}
accessibilityLabel="increment"
color="blue"
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
title: {
fontSize: 20,
fontWeight: 'bold',
},
separator: {
marginVertical: 30,
height: 1,
width: '80%',
},
});
Error Message
App Output:
import React, { useState } from 'react';
import { StyleSheet, Button, Alert, Text, View } from 'react-native';
export default function TabTwoScreen() {
// ๐ You are using functional components so use the useState hook.
const [counter, setCounter] = useState(0);
const but1 = () => {
// ๐then you can increase the counter like below
setCounter(counter + 1);
};
return (
<View style={styles.container}>
<Text style={styles.title}>Counter:{counter}</Text>
<Button
title="Increment"
onPress={but1}
accessibilityLabel="increment"
color="blue"
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
title: {
fontSize: 20,
fontWeight: 'bold',
},
});
And if you want to use Class based component then here is the implementation:
import React, { useState, Component } from 'react';
import { StyleSheet, Button, Alert, Text, View } from 'react-native';
export default class TabTwoScreen extends Component {
constructor(props) {
super(props);
this.state = {
counter: 0,
};
}
but1 = () => {
this.setState({ counter: this.state.counter + 1 });
};
render() {
return (
<View style={styles.container}>
<Text style={styles.title}>Counter:{this.state.counter}</Text>
<Button
title="Increment"
onPress={this.but1}
accessibilityLabel="increment"
color="blue"
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
title: {
fontSize: 20,
fontWeight: 'bold',
},
});
Working App: Expo Snack
Please take a look at https://reactjs.org/docs/react-component.html#setstate
Remove this from your code and let only state.count + 1
An example I did in freedcodecamp.
handleChange(event){
//event.target.value
this.setState({
input: event.target.value
});
}
// Change code above this line
render() {
return (
<div>
{ /* Change code below this line */}
<input value={this.state.input} onChange={(e) => this.handleChange(e)}/>
That is because you are using a function component. You have to either use a class based component (React class and function components) or switch over to React hooks with the useState hook.
Here's the example with a class based component:
import * as React from 'react';
import { StyleSheet, Button, Alert } from 'react-native';
import EditScreenInfo from '../components/EditScreenInfo';
import { Text, View } from '../components/Themed';
export default class TabTwoScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 0
}
}
but1() {
this.setState({ counter: this.state.counter + 1 });
};
render() {
return (
<View style={styles.container}>
<Text style={styles.title}>Counter:{state.counter}</Text>
<Button
title="Increment"
onPress={this.but1}
accessibilityLabel="increment"
color="blue"
/>
</View>
);
}
}
And here's with React hooks:
import React, {useState} from 'react';
import { StyleSheet, Button, Alert } from 'react-native';
import EditScreenInfo from '../components/EditScreenInfo';
import { Text, View } from '../components/Themed';
export default function TabTwoScreen() {
const [counter, setCounter] = useState(0);
const but1 = () => {
setCounter(counter + 1);
};
return (
<View style={styles.container}>
<Text style={styles.title}>Counter:{counter}</Text>
<Button
title="Increment"
onPress={but1}
accessibilityLabel="increment"
color="blue"
/>
</View>
);
}
I want to use relamDb in my react native expo project. I run the following command to install realm in my project-
npm install --save realm
it doesn't show any error while installing. After installing, in my project I have created two classes - App.js and TodoListComponent.js
App.js
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import TodoListComponent from './components/TodoListComponent';
export default class App extends React.Component {
render() {
return (
<View style={styles.container}>
<TodoListComponent/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
TodoListComponent.js
import React, { Component } from 'react';
import { View, FlatList, Text, TouchableOpacity, StyleSheet, Alert } from 'react-native';
import { updateTodoList, deleteTodoList, queryAllTodoLists } from '../databases/allSchemas';
import realm from '../databases/allSchemas';
import Swipeout from 'react-native-swipeout';
import HeaderComponent from './HeaderComponent';
import PopupDialogComponent from './PopupDialogComponent';
let FlatListItem = props => {
const { itemIndex, id, name, creationDate, popupDialogComponent, onPressItem } = props;
showEditModal = () => {
popupDialogComponent.showDialogComponentForUpdate({
id, name
});
}
showDeleteConfirmation = () => {
Alert.alert(
'Delete',
'Delete a todoList',
[
{
text: 'No', onPress: () => { },//Do nothing
style: 'cancel'
},
{
text: 'Yes', onPress: () => {
deleteTodoList(id).then().catch(error => {
alert(`Failed to delete todoList with id = ${id}, error=${error}`);
});
}
},
],
{ cancelable: true }
);
};
return (
<Swipeout right={[
{
text: 'Edit',
backgroundColor: 'rgb(81,134,237)',
onPress: showEditModal
},
{
text: 'Delete',
backgroundColor: 'rgb(217, 80, 64)',
onPress: showDeleteConfirmation
}
]} autoClose={true}>
<TouchableOpacity onPress={onPressItem}>
<View style={{ backgroundColor: itemIndex % 2 == 0 ? 'powderblue' : 'skyblue' }}>
<Text style={{ fontWeight: 'bold', fontSize: 18, margin: 10 }}>{name}</Text>
<Text style={{ fontSize: 18, margin: 10 }} numberOfLines={2}>{creationDate.toLocaleString()}</Text>
</View>
</TouchableOpacity>
</Swipeout >
);
}
export default class TodoListComponent extends Component {
constructor(props) {
super(props);
this.state = {
todoLists: []
};
this.reloadData();
realm.addListener('change', () => {
this.reloadData();
});
}
reloadData = () => {
queryAllTodoLists().then((todoLists) => {
this.setState({ todoLists });
}).catch((error) => {
this.setState({ todoLists: [] });
});
console.log(`reloadData`);
}
render() {
return (<View style={styles.container}>
<HeaderComponent title={"Todo List"}
hasAddButton={true}
hasDeleteAllButton={true}
showAddTodoList={
() => {
this.refs.popupDialogComponent.showDialogComponentForAdd();
}
}
/>
<FlatList
style={styles.flatList}
data={this.state.todoLists}
renderItem={({ item, index }) => <FlatListItem {...item} itemIndex={index}
popupDialogComponent={this.refs.popupDialogComponent}
onPressItem={() => {
alert(`You pressed item `);
}} />}
keyExtractor={item => item.id}
/>
<PopupDialogComponent ref={"popupDialogComponent"} />
</View>);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
justifyContent: 'flex-start',
},
flatList: {
flex: 1,
flexDirection: 'column',
}
});
After these coding, when I run the application it shows the following error-
missing Realm constructor. Did you run "react-native link realm" ? Please see https://realm.io/docs/react-native/latest/#missing-realm-constructor for troubleshooting
I have tried to find out problem from the below links-
https://github.com/realm/realm-js/issues/1407
https://github.com/realm/realm-js/issues/1340
But none of these were helpful to me. So, it would be very nice if some one helps me to know how to use realmDb in React native expo project.
Expo does not support realm.
You will have to eject from expo and then start using realm
Please note that Expo does not support Realm, From the docs.
Old Question, but you can now by using their template:
https://www.npmjs.com/package/#realm/expo-template-ts
https://www.mongodb.com/docs/realm/sdk/react-native/quick-start-expo/
Problem with stack navigation between the screens.
I am displaying data on my 'SveKategorije' screen.
It's basically categories buttons, when i click on button i just want to show another screen for now, but it is not working for some reason.
When i put onPress={() => this.props.navigation.navigate('screenname')}
it gives me this
error
I am using (react-native - 0.57.7)
Here is router.js code (where i declare my routes)
import React from 'react';
import { View, Text, Button } from "react-native";
import { createBottomTabNavigator, createStackNavigator } from "react-navigation";
import { Icon } from 'react-native-elements';
//TABS
import Categories from '../tabs/categories';
import Home from '../tabs/home';
import Me from '../tabs/me';
//screens for CATEGORIES
import ViceviPoKategoriji from '../components/Ispis/ViceviPoKategoriji';
//CATEGORIES STACK
export const categoriesFeedStack = createStackNavigator({
SveKategorije: {
screen: Categories,
navigationOptions: {
title: 'KATEGORIJE',
},
},
ViceviPoKategoriji: {
screen: ViceviPoKategoriji,
}
});
//TABS
export const Tabs = createBottomTabNavigator({
Categories: {
screen: categoriesFeedStack,
navigationOptions: {
title: 'Kategorije',
label: 'Kategorije',
tabBarIcon: ({ tintColor }) => <Icon name="list" size={35} color={tintColor} />,
}
},
Home: {
screen: Home,
navigationOptions: {
title: 'Pocetna',
label: 'Kategorije',
tabBarIcon: ({ tintColor }) => <Icon name="home" size={35} color={tintColor} />,
}
},
Me: {
screen: Me,
navigationOptions: {
title: 'Profil',
label: 'Kategorije',
tabBarIcon: ({ tintColor }) => <Icon name="account-circle" size={35} color={tintColor} />,
}
},
},
{
initialRouteName: "Home",
showIcon: true
},
);
Here is 'SveKategorije' screen
import React from 'react';
import { StyleSheet, Text, View, ActivityIndicator, ScrollView, Button } from 'react-native';
import { createStackNavigator, createAppContainer, StackNavigator, navigate } from 'react-navigation';
export default class SveKategorije extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
dataSource: null
}
}
componentDidMount() {
return fetch('http://centarsmijeha.com/api/allCategories')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson.data,
})
})
.catch((error) => {
console.log(error)
});
}
render() {
if (this.state.isLoading) {
return (
<View style={styles.container}>
<ActivityIndicator />
</View>
)
} else {
let data = this.state.dataSource.map((val, key) => {
return (
<View key={key} style={styles.item}>
<Button
onPress={() => this.props.navigation.navigate('ViceviPoKategoriji')}
title={val.categoryName}
/>
</View>
);
});
return (
<ScrollView>
{data}
</ScrollView >
);
}
}
}
//CSS
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
width: '100%'
},
item: {
flex: 1,
alignSelf: 'stretch',
width: '100%',
textAlign: 'center',
alignItems: 'center',
justifyContent: 'center'
}
});
and here is 'ViceviPoKategoriji' screen ( the screen that should be displayed on click of any buttons from 'SveKategorije' screen )
import React from 'react';
import { StyleSheet, Text, View, ActivityIndicator, ScrollView } from 'react-native';
export default class ViceviPoKategoriji extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
dataSource: null,
}
}
componentDidMount() {
return fetch('http://centarsmijeha.com/api/jokesByCategory/16')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson.data,
})
})
.catch((error) => {
console.log(error)
});
}
render() {
if (this.state.isLoading) {
return (
<View style={styles.container}>
<ActivityIndicator />
</View>
)
} else {
let data = this.state.dataSource.map((val, key) => {
return <View key={key} style={styles.item}><Text>{val.jokeText}</Text></View>
});
return (
<ScrollView>
{data}
</ScrollView >
);
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
item: {
flex: 1,
alignSelf: 'stretch',
marginTop: 50,
marginRight: '15%',
marginLeft: '15%',
width: '70%',
textAlign: 'center',
alignItems: 'center',
justifyContent: 'center',
borderBottomWidth: 1,
borderBottomColor: '#eee'
}
});
React-navigation is props based navigation.
I think your component don't have navigation props.
Please check whether your component have navigation props.
do
render() {
console.log(this.props.navigation)
// or debugger
return (
If result of console.log is undefined, then add 'import SveKategorije' to your routing file.
You have to do few more setups for navigating from the component.You can get access to a navigator through a ref and pass it to the NavigationService which we will later use to navigate.
https://reactnavigation.org/docs/en/navigating-without-navigation-prop.html
In my case I accidentally used this.props.navigation inside functional component. If any one made a mistake like this, will check u r code once again.
i am new to react and trying to learn it by myself , i am facing problem in navigating user back to root screen from nested stck navigator screen .
Here is some of my classes :-
index.android.js :-
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
StatusBar,
View
} from 'react-native';
import {LoginStack} from './login/loginregisterrouter';
import {StackNavigator } from 'react-navigation';
class reactNavigationSample extends Component {
render(){
return (
<LoginStack/>
);
}
}
AppRegistry.registerComponent('MssReactDemo', () => reactNavigationSample);
loginregisterrouter :-
import React from 'react';
import {StackNavigator } from 'react-navigation';
import LoginScreen from './LoginScreen';
import RegisterScreen from './RegisterScreen';
import NavigationContainer from './navigationContainer';
export const LoginStack = StackNavigator({
LoginScreen: {
screen: LoginScreen,
navigationOptions: {
title: 'LoginScreen',
}
},
RegisterScreen: {
screen: RegisterScreen,
navigationOptions: ({ navigation }) => ({
title: 'RegisterScreen',
}),
},NavigationContainer: {
screen: NavigationContainer,
navigationOptions: ({ navigation }) => ({
title: 'NavigationContainer', header: null,
}),
},
});
Navigationcontainer.js :-
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
StatusBar,
View
} from 'react-native';
import {EasyRNRoute,} from '../parent';
import {StackNavigator } from 'react-navigation';
export default class NavigationContainer extends Component {
render(){
return (
<EasyRNRoute/>
);
}
}
parent.js :-
import React, { Component } from 'react';
import {
StyleSheet,
Text,
StatusBar,
View
} from 'react-native';
import App from './app';
import DrawerMenu from './Drawer/drawer-toolbar-android';
import BookmarkView from './Pages/bookmark';
import ClientView from './Pages/client';
import InfoView from './Pages/info';
import SettingsView from './Pages/setting';
import { DrawerNavigator, StackNavigator } from 'react-navigation';
export const stackNavigator = StackNavigator({
Info: { screen: InfoView },
Settings: {screen: SettingsView },
Bookmark: {screen: BookmarkView },
Connections: {screen: ClientView},
}, {
headerMode: 'none'
});
export const EasyRNRoute = DrawerNavigator({
Home: {
screen: App,
},
Stack: {
screen: stackNavigator
}
}, {
contentComponent: DrawerMenu,
contentOptions: {
activeTintColor: '#e91e63',
style: {
flex: 1,
paddingTop: 15,
}
}
});
Drawer-toolbar-android.js :-
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
StatusBar,
View
} from 'react-native';
import { NavigationActions } from 'react-navigation'
import { COLOR, ThemeProvider, Toolbar, Drawer, Avatar } from 'react-native-material-ui';
import Container from '../Container';
import LoginScreen from '../login/LoginScreen';
const uiTheme = {
palette: {
primaryColor: COLOR.green500,
accentColor: COLOR.pink500,
},
toolbar: {
container: {
height: 70,
paddingTop: 20,
},
},
avatar: {
container: {
backgroundColor: '#333'
}
}
};
export default class DrawerMenu extends Component {
constructor(props, context) {
super(props, context);
this.state = {
active: 'people',
};
}
handleLogoutPress = () => {
// AsyncStorage.setItem('SignedUpuser', '');
this.props
.navigation
.dispatch(NavigationActions.reset(
{
index: 0,
actions: [
NavigationActions.navigate({ routeName: 'LoginScreen'})
]
}));
// this.props.navigation.dispatch(NavigationActions.back());
};
_setInfoActive() {
this.setState({ active: 'info' });
}
render() {
return (
<ThemeProvider uiTheme={uiTheme}>
<Container>
<StatusBar backgroundColor="rgba(0, 0, 0, 0.2)" translucent />
<Toolbar
leftElement="arrow-back"
onLeftElementPress={() => this.props.navigation.navigate('DrawerClose')}
centerElement="Menu"
/>
<View style={styles.container}>
<Drawer>
<Drawer.Header >
<Drawer.Header.Account
style={{
container: { backgroundColor: '#fafafa' },
}}
avatar={<Avatar text={'S'} />}
// accounts={[
// { avatar: <Avatar text="H" /> },
// { avatar: <Avatar text="L" /> },
// ]}
footer={{
dense: true,
centerElement: {
primaryText: 'Siddharth',
secondaryText: 'I am DONE now',
},
}}
/>
</Drawer.Header>
<Drawer.Section
style={{
label: {color: '#0000ff'}
}}
divider
items={[
{
icon: 'bookmark-border', value: 'Bookmarks',
active: this.state.active == 'bookmark',
onPress: () => {
this.setState({ active: 'bookmark' });
this.props.navigation.navigate('Bookmark');
},
},
{
icon: 'people', value: 'Connections',
active: this.state.active == 'Connection',
onPress: () => {
this.setState({ active: 'Connection' });
this.props.navigation.navigate('Connections');
},
},
]}
/>
<Drawer.Section
title="Personal"
items={[
{
icon: 'info', value: 'Info',
active: this.state.active == 'info',
onPress: () => {
this.setState({ active: 'info' });
//this.props.navigation.navigate('DrawerClose');
this.props.navigation.navigate('Info');
},
},
{
icon: 'settings', value: 'Settings',
active: this.state.active == 'settings',
onPress: () => {
this.setState({ active: 'settings' });
this.props.navigation.navigate('Settings');
},
},
{
icon: 'logout', value: 'Logout',
active: this.state.active == 'logout',
onPress: () => {
this.handleLogoutPress();
},
},
]}
/>
</Drawer>
</View>
</Container>
</ThemeProvider>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
},
header: {
backgroundColor: '#455A64',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
The above is the stack architecture i am using inside my application and as you can see that my Main screen is LOGIN screen and i do have option for LOGOUT from application in my Drawer(side menu). What i eaxtly want is that when user click on logout he/she should get redirected to LOGIN screen . i have googled about this and got to know about two ways of doing it , but both the ways are not working for me , may be i am using them in wrong way. so i am here to seek your help .
The two methods are :-
1)
this.props
.navigation
.dispatch(NavigationActions.reset(
{
index: 0,
actions: [
NavigationActions.navigate({ routeName: 'LoginScreen'})
]
}));
2) this.props.navigation.dispatch(NavigationActions.back());
this question may seems silly to you but i am really stuck at this point and just want to know how can i figure this out.Any help would be greatly Appreciated!!!!
Thanks in advance.
After trying almost everything, I've found the solution that worked for me:
this.props.navigation.popToTop(); // go to the top of the stack
this.props.navigation.goBack(null); // now show the root screen
Modal StackNavigator containing a Dismissable StackNavigator
Requires: react-navigation version: 1.0.0
Goal: Navigate from App TabNavigator to Screen 1 to Screen 2 to Screen N and then directly back to App TabNavigator.
Navigation hierarchy:
RootNavigator StackNavigator {mode: 'modal'}
App TabNavigator
TabA Screen
TabB Screen
TabC Screen
ModalScreen Screen
ModalStack DismissableStackNavigator
Screen 1 ModalStackScreen
Screen 2 ModalStackScreen
Screen N ModalStackScreen
Demo
package.json
{
"name": "HelloWorld",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"dependencies": {
"react": "16.0.0-alpha.6",
"react-native": "0.44.0",
"react-navigation": "^1.0.0"
},
"devDependencies": {
"babel-jest": "20.0.3",
"babel-preset-react-native": "1.9.2",
"jest": "20.0.3",
"react-test-renderer": "16.0.0-alpha.6"
},
"jest": {
"preset": "react-native"
}
}
index.ios.js (or index.android.js)
import React from 'react'
import {
AppRegistry,
Button,
Text,
View
} from 'react-native'
import {
StackNavigator,
TabNavigator
} from 'react-navigation'
class TabA extends React.Component {
state = {
startScreen: 'none',
returnScreen: 'none'
}
render () {
return (
<View style={{ padding: 40, paddingTop: 64 }}>
<Text style={{ fontSize: 20 }}>{this.constructor.name}</Text>
<Text>startScreen: {this.state.startScreen}</Text>
<Text>returnScreen: {this.state.returnScreen}</Text>
<Button
title="Open ModalScreen"
onPress={() => this.props.navigation.navigate('ModalScreen', {
startScreen: this.constructor.name,
setParentState: (state) => this.setState(state)
})}
/>
<Button
title="Open ModalStack"
onPress={() => this.props.navigation.navigate('ModalStack', {
startScreen: this.constructor.name,
setParentState: (state) => this.setState(state)
})}
/>
</View>
)
}
}
class TabB extends TabA {}
class TabC extends TabA {}
class ModalScreen extends React.Component {
render () {
const {
startScreen,
setParentState
} = this.props.navigation.state.params
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text style={{ fontSize: 20 }}>{this.constructor.name}</Text>
<Button
title="Close"
onPress={() => {
setParentState({
startScreen,
returnScreen: this.constructor.name
})
this.props.navigation.goBack()
}}
/>
</View>
)
}
}
const DismissableStackNavigator = (routes, options) => {
const StackNav = StackNavigator(routes, options)
return class DismissableStackNav extends React.Component {
static router = StackNav.router
render () {
const { state, goBack } = this.props.navigation
const screenProps = {
...this.props.screenProps,
dismissStackNav: () => goBack(state.key)
}
return (
<StackNav
screenProps={screenProps}
navigation={this.props.navigation}
/>
)
}
}
}
class ModalStackScreen extends React.Component {
render () {
const screenNumber = this.props.navigation.state.params && this.props.navigation.state.params.screenNumber || 0
const {
startScreen,
setParentState
} = this.props.navigation.state.params
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text style={{ fontSize: 20 }}>{this.constructor.name + screenNumber}</Text>
<View style={{
flexDirection: 'row',
justifyContent: 'space-between'
}}>
<Button
title={screenNumber === 0 ? "Close" : "Back"}
onPress={() => this.props.navigation.goBack(null)}
/>
<Button
title="Save"
onPress={() => {
setParentState({
startScreen,
returnScreen: this.constructor.name + screenNumber
})
this.props.screenProps.dismissStackNav()
}}
/>
<Button
title="Next"
onPress={() => this.props.navigation.navigate('ModalStackScreen', {
screenNumber: screenNumber + 1,
startScreen,
setParentState
})}
/>
</View>
</View>
)
}
}
const TabNav = TabNavigator(
{
TabA: {
screen: TabA
},
TabB: {
screen: TabB
},
TabC: {
screen: TabC
}
}
)
const ModalStack = DismissableStackNavigator(
{
ModalStackScreen: {
screen: ModalStackScreen
}
},
{
headerMode: 'none'
}
)
const RootStack = StackNavigator(
{
Main: {
screen: TabNav,
},
ModalScreen: {
screen: ModalScreen,
},
ModalStack: {
screen: ModalStack
}
},
{
mode: 'modal',
headerMode: 'none'
}
)
class App extends React.Component {
render () {
return <RootStack />
}
}
AppRegistry.registerComponent('HelloWorld', () => App)
Previous Answer
This solution is a sledgehammer. It causes the screen of the default tab in the TabNavigator to unmount and then mount again. If the Screen a tab launching the Modal with the StackNavigator passes some callbacks to update it's state, these callbacks will be called when the Screen is unmounted.
The solution was to add key: null to the reset object:
this.props.navigation.dispatch(NavigationActions.reset({
index: 0,
key: null,
actions: [
NavigationActions.navigate({ routeName: 'App'})
]
}))
I was tipped off by this comment.
(FYI - I got here via your comment asking for help.)
As per react navigation doc you can go to any stack by following ways:
check the following link for more details
React-navigation stack action link
1. import { StackActions, NavigationActions } from 'react-navigation';
const resetAction = StackActions.reset({
index: 0,
actions: [NavigationActions.navigate({ routeName: 'Profile' })],
});
this.props.navigation.dispatch(resetAction);
If you have a stack for profile then you can also go through like this check following link nested react navigation
import { NavigationActions } from 'react-navigation';
const navigateAction = NavigationActions.navigate({
routeName: 'Profile',
params: {},
action: NavigationActions.navigate({ routeName: 'SubProfileRoute' }),
});
this.props.navigation.dispatch(navigateAction);
(React Navigation 5.x) I had the problem of conditionally rendering the Screens like the example in
"https://reactnavigation.org/docs/en/auth-flow.html" As I understand, meant that the Stack navigators were not "rendered" and thus are not able to find each other. What I did was the below and in the logout page:
navigation.replace('SplashScreen')
My logic was: SplashScreen (Check for AsyncStorage Token),
if (token){
navigation.navigate('App')
}else{
navigation.navigate('StartScreen')
}
In StartScreen, just navigate to Signin or Register where you go back to App if login is successful.
As a reference,
function AppBottomNavigator(){
return(
<AppNavigator.Navigator
initialRouteName={'Home'} ...}>
<AppNavigator.Screen name='A' component={ScreenA}/>
<AppNavigator.Screen name='B' component={ScreenB}/>
<AppNavigator.Screen name='C' component={ScreenC}/>
<AppNavigator.Screen name='D' component={ScreenD}/>
<AppNavigator.Screen name='E' component={ScreenE}/>
</AppNavigator.Navigator>
)
}
export default App stuff...
...return(
<AuthContext.Provider value={authContext}>
<NavigationContainer>
<AuthStack.Navigator screenOptions={{headerShown:false}}>
<>
<AuthStack.Screen name='SplashScreen' component={SplashScreen}/>
<AuthStack.Screen name='StartScreen' component={StartScreen} />
<AuthStack.Screen name='SignIn' component={SignIn} />
<AuthStack.Screen name='Register' component={Register} />
<AuthStack.Screen name='App' component={AppBottomNavigator}/>
</>
</AuthStack.Navigator>
</NavigationContainer>
</AuthContext.Provider>
)
I am also quite new to this but it worked so if someone else has a safer/tidier/general solution, I would quite like to know, too.