Passing props to a component using StackNavigator in React Native - react-native

import React, {Component} from 'react'
import { StackNavigator } from 'react-navigation'
import {connect} from 'react-redux'
import {getAllUsers} from '../actions'
import {List, ListItem} from 'react-native-elements'
import { StyleSheet, Text, View, FlatList } from 'react-native'
const UserDetail = () => {
<View>
<Text>User Detail</Text>
</View>
}
const Home = ({ navigation }) => (
<List>
{typeof users === 'string' &&
<FlatList
data={users}
/>
}
</List>
)
const Stack = StackNavigator({
Home: {
screen: Home
},
UserDetail: {
screen: UserDetail
}
})
class MainScreen extends Component {
componentDidMount(){
this.setState({ users : this.props.getAllUsers() })
}
render() {
const users = typeof this.props.decks === 'string'
? Object.values(JSON.parse(this.props.users)) : ''
return(
<Stack />
)
}
}
function mapStateToProps(users) {
return {
users: users,
}
}
function mapDispatchToProps(dispatch) {
return {
getAllUsers: () => dispatch(getAllUsers()),
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(MainScreen)
I have two questions:
1) I want to pass the users props from MainScreen component to Home component and later on also to UserDetail component. But I could not see any example on that on React Navigation documentation except for ScreenProps.
2) If I go to UserDetail and let's say it would be a separate component. And let's say it would call another component. How could it go back to Home for example?
I'm using Redux by the way also here and there are some who suggest to do it in Redux but still I could not make it work also. I am fairly new to React Native or React for that matter, but I could not find a definitive answer so far on this above questions.

Related

How to fix an Objects are not valid as a React child Error?

I am very new to programming with React-native, and I was wondering if anyone could explain how I should fix this error? I was following along with a tutorial and had an error come up due to this section of code, even though it matched the tutorial code.
Here is the section of code:
import React, { createContext, useContext } from "react";
import * as Google from "expo-google-app-auth";
const AuthContext = createContext({});
export const AuthProvider = ({ children }) => {
const signInWithGoogle = async() => {
await Google.logInAsync
}
return (
<AuthContext.Provider
value={{
user: null,
}}
>
{children}
</AuthContext.Provider>
);
};
export default function useAuth() {
return useContext(AuthContext);
}
These other two sections may be relevant as well:
Root of the App:
import React from 'react';
import { Text, View, SafeAreaView, Button, Alert } from 'react-native';
import AuthProvider from "./hooks/useAuth";
import StackNavigator from "./StackNavigator";
import { NavigationContainer} from "#react-navigation/native";
// Function for creating button
export default function App() {
return (
<NavigationContainer>
<AuthProvider>
<StackNavigator />
</AuthProvider>
</NavigationContainer>
);
}
This is my code for the Login Screen:
import React from 'react';
import { View, Text } from 'react-native';
import useAuth from '../hooks/useAuth';
const LoginScreen = () => {
const { user } = useAuth();
console.log(user);
return (
<View>
<Text>
Login to the app
</Text>
</View>
);
};
export default LoginScreen
This is the error that appears:
Error: Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead.
I suggest you auth with firebase. it makes easier this things.

undefined is not a function (evaluating 'navigation.dispatch')

I am trying to navigate to the first page after user logout!
and getting this error:
undefined is not a function (evaluating 'navigation.dispatch').
my action creator code is as follows:
import {NavigationActions} from 'react-navigation';
import {AsyncStorage} from 'react-native';
import {applyMiddleware as dispatch} from "redux";
export const userRemove = (navigation) => {
AsyncStorage.removeItem('user');
const navigateAction = NavigationActions.navigate({
routeName: 'First',
props: {}
});
navigation.dispatch(navigateAction);
};
I have called this action from sideBar of component. The component code is correct since that AsyncStorage.removeItem('user') is working correctly!
sorry for bad grammar. I can't write in english better than this error message here
my component code here:
import React, {Component} from 'react';
import {
Container,
Content,
Footer,
FooterTab,
Button,
Icon
} from 'native-base';
import {userRemove} from '../actions/sideBarAction';
import {connect} from "react-redux";
import {bindActionCreators} from "redux";
class SideBar extends Component {
constructor(props) {
super(props);
}
logout() {
userRemove(this.props.navigation);
}
render() {
return (
<Container>
<Content>
...
</Content>
<Footer>
<FooterTab>
<Button onPress={this.logout.bind(this)}>
<Icon name="logout"/>
</Button>
</FooterTab>
</Footer>
</Container>
)
}
}
const mapStateToProps = state => {
return {
username: state.home.username,
password: state.home.password,
score: state.home.score,
}
};
const mapDispatchToProps = dispatch => {
return Object.assign({dispatch: dispatch},
bindActionCreators(userRemove, dispatch));
};
connect(mapStateToProps, mapDispatchToProps)(SideBar);
Is your component added to you main navigator? If not see if you can add.
You can also wrap your component with withNavigation function from react-navigation. That will make sure you have valid navigation prop.
import { withNavigation } from react-navigation;
...
connect(mapStateToProps, mapDispatchToProps)(withNavigation(SideBar));
Alternatively, you may pass this.props.navigation from parent component too.

React navigation. Render extra views on top of navigator

I'm trying to create a React Native app that renders an area with interchangeable screens and fixed view with some additional data/menu. I tried this solution form official React Navigation, but I can't make it work.
import React, { Component } from "react";
import {createStackNavigator} from 'react-navigation';
import { Text, View,} from 'react-native';
import Details from './DetailsScreen';
import MainScreen from './MainScreen';
const RootStack = createStackNavigator({
Main: {screen: MainScreen,
navigationOptions: {
header: null
}
},
Details: {
screen: Details,
},);
class App extends Component {
static router = {
...RootStack.router,
getStateForAction: (action, lastState) => {
return MyStack.router.getStateForAction(action, lastState);
}
};
render() {
const { navigation } = this.props;
return(
<View>
<Text>Foo</Text> //this is rendering
<RootStack navigation={navigation}/> //this is not
</View>);
}
}
export default App;
Article form link suggests that I can wrap object created with createStackNavigator() in a parent View, but it renders only when it is the only thing returned from render(), otherwise it seems to be ignored. Example from link claims that it is possible to "render additional things", but I can't make it work. Is it possible to do this way?
You can try this:
//wrapper.js
function wrapNavigator(Navigator, Wrapper, wrapperProps = {}) {
const WrappedComponent = props => (
<Wrapper { ...props, ...wrapperProps}>
<Navigator {...props} />
</Wrapper>
);
WrappedComponent.router = Navigator.router;
WrappedComponent.navigationOptions = Navigator.navigationOptions;
return WrappedComponent;
};
//app.js
const App = (props) => <View>
<Text>Some text...</Text>
{children}
</View>
export default wrapNavigator(Stack, App);
But this will not work if there are no parent navigator for App component.

undefined is not an object this.props

I try to use navigation between screen in my RN app. This is my code :
INDEX.ANDROID.JS :
import React, { Component } from 'react';
import {
AppRegistry,
Text,
View ,
Button
} from 'react-native';
import {StackNavigator} from 'react-navigation';
import Login from './app/components/Todo';
const SimpleApp = StackNavigator({
Login: { screen: Todo },
});
export default class aap extends Component {
static navigationOptions = { title: 'Welcome', };
render() {
const { navigate } = this.props.navigation;
return (
<Button onPress ={() => navigate('Todo') } title="go"/>
);
}
}
AppRegistry.registerComponent('aap', () => aap);
here is the code of the second screen TODO.JS
import React, { Component } from 'react';
import {
AppRegistry,
Text,
View ,
Button
} from 'react-native';
export default class Todo extends Component {
render() {
return (
<View>
<Text>
Here is my text
</Text>
</View>
);
}
}
When running my code i get an error : undefined is not an object this.props.naviagtion.
Any help is appreciated
You are not using StackNavigator correctly.
Like #xght said, you should be registering SimpleApp instead of aap. Also, you should be using aap as the initial route to your StackNavigator SimpleApp.
This should look something like this:
import React, { Component } from 'react';
import {
AppRegistry,
Text,
View ,
Button
} from 'react-native';
import {StackNavigator} from 'react-navigation';
import Todo from './app/components/Todo';
class aap extends Component {
static navigationOptions = { title: 'Welcome', };
render() {
const { navigate } = this.props.navigation;
return (
<Button onPress ={() => navigate('Todo') } title="go"/>
);
}
}
const SimpleApp = StackNavigator({
Login: { screen: aap },
Todo: { screen: Todo },
});
AppRegistry.registerComponent('aap', () => SimpleApp);
You registered the wrong component, so the navigator SimpleApp doesn't pass the navigation prop to your component.
Replace
AppRegistry.registerComponent('aap', () => aap); by:
AppRegistry.registerComponent('aap', () => SimpleApp);
And also you forgot to add your aap component in SimpleApp routes. And your import Login from './app/components/Todo';is wrong: Login is the name of the route in SimpleApp, and Todo is the name of the component, so you need to replace it by import Todo...

Navigation in React Router v4 Native Not Changing Scenes

I'm using React Router for a React Native app. Not sure what I'm missing here but I install react-router-native and require the history package, and setup a couple methods that just push a new route onto the stack but nothing happens. I console.log('clicked'); to check that it's firing and it is so not sure what's wrong.
import React, { Component } from 'react';
import { View } from 'react-native';
import Splash from './Splash';
import createHistory from 'history/createMemoryHistory';
const history = createHistory();
class SplashContainer extends Component {
goToLogin = () => {
history.push('/Login');
}
goToRegister = () => {
history.push('/SignUp');
}
render () {
console.log(history)
return (
<Splash
goToLogin={this.goToLogin}
goToRegister={this.goToRegister}
/>
);
}
}
export default SplashContainer;
import React from 'react';
import { StyleSheet, View, Text } from 'react-native';
import { Button } from 'native-base';
import { Link } from 'react-router-native';
import PropTypes from 'prop-types';
const Splash = (props) => {
console.log(props)
return (
<View style={styles.container}>
<Button light block onPress={props.goToLogin}>
<Text>Login</Text>
</Button>
<Button dark block bordered style={{marginTop: 10}} onPress={props.goToRegister}>
<Text>Register</Text>
</Button>
</View>
);
}
Splash.propTypes = {
goToLogin: PropTypes.func.isRequired,
goToRegister: PropTypes.func.isRequired
}
export default Splash;
I don't know your Router config, but your methods should be:
goToLogin = () => {
const { history } = this.props
history.push('/Login');
}
history will passed down via props of component inside Router's stack.