I'm working on a React Native app w/Meteor and have been trying out a few npm packages to determine which can best handle both native tabbed and drawer navigation. The react-native-navigation package seems to do a really great job - but it seems to be bypassing the logic I had been using to determine the user logged in state on startup.
Here's the App.js file, which is imported into both the Android and iOS index files on load:
import React from 'react';
import Meteor, { createContainer } from 'react-native-meteor';
import LoggedOut from './layouts/LoggedOut';
import LoggedIn from './layouts/LoggedIn';
import Loading from './components/Loading';
import config from './config';
Meteor.connect(config.METEOR_URL);
const MyApp = (props) => {
const { status, user, loggingIn } = props;
if (status.connected === false || loggingIn) {
return <Loading />;
} else if (user !== null) {
return <LoggedIn />;
} else {
return <LoggedOut />;
}
};
MyApp.propTypes = {
status: React.PropTypes.object,
user: React.PropTypes.object,
loggingIn: React.PropTypes.bool,
};
export default createContainer(() => {
return {
status: Meteor.status(),
user: Meteor.user(),
loggingIn: Meteor.loggingIn(),
};
}, MyApp);
And I've placed the react-native-navigation Navigation.startTabBasedApp() code in the <LoggedIn/> Component as such:
import { Navigation } from 'react-native-navigation';
import { registerScreens } from '../helpers/navigation';
registerScreens();
Navigation.startTabBasedApp({
tabs: [
{
label: 'Records',
screen: 'screen.Records',
icon: require('../images/NavigatorMenuIcon1.png'),
selectedIcon: require('../images/NavigatorMenuIcon1.png'),
title: 'Records'
},
{
label: 'Favorites',
screen: 'screen.Favorites',
icon: require('../images/NavigatorMenuIcon2.png'),
selectedIcon: require('../images/NavigatorMenuIcon2.png'),
title: 'Favorites'
},
],
drawer: {
left: {
screen: 'screen.Menu'
},
},
passProps: {},
});
The react-native-navigation package does require a bit of Xcode configuration for iOS, including adding the native files of the dependency react-native-controllers to the Xcode project; and modifying the AppDelegate.m file... Though I'm unable to figure out why the startup configuration is effectively being ignored.
UPDATE:
I found a closed issue at react-native-navigation that explains how to use layouts for hybrid (tabbed/single page) apps: you simply start a new "app" instance. For example, in my app, I want the logout function to redirect to the Sign In screen.
This can be accomplished by calling a function that starts a new single screen app instance (Navigation.startSingleScreenApp). I tested this and confirm it works for LogOut. A similar solution can be employed for the sign in / start screens.
handleSignOut(props) {
Meteor.logout(props);
Navigation.startSingleScreenApp ({
screen: {
screen: 'screen.SignIn', // unique ID registered with Navigation.registerScreen
navigatorStyle: {navBarHidden: true}, // override the navigator style for the screen, see "Styling the navigator" below (optional)
navigatorButtons: {} // override the nav buttons for the screen, see "Adding buttons to the navigator" below (optional)
},
});
The issue persists on App startup, however, as the Navigation apps are loading as they're imported into the App/index file. Essentially, the if/else logic defining app state is being ignored.
Related
I had to refactor recently the navigation inside my React Native App using React Navigation.
Indeed, I have several navigators inside my app for different purposes: screens when not connected, screens when connected and some screens that should be available in both situations
(e.g. terms of use).
So my question is the following, if I have this pattern, how can I for example navigate from TermsOfUse to Register without going back to Welcome?
I can't use navigate.goBack() or navigation.navigate('Register') since those screens are not in the same StackNavigator, and duplicate the TermsOfUse in both navigators would be quite dirty.
// Screens
const NotConnectedScreens = {
Welcome: { screen: WelcomeScreen },
Register: { screen: RegisterScreen },
}
const ConnectedScreens = {
Homepage: { screen: HomepageScreen },
Tutorial: { screen: TutorialScreen },
}
const OthersScreens = {
TermsOfUse: { screen: TermsOfUseScreen },
}
// Stacks
const NotConnectedStack = createStackNavigator(NotConnectedScreens, {
initialRouteName: 'Welcome',
})
const ConnectedScreens = createStackNavigator(ConnectedScreens, {
initialRouteName: 'Homepage',
})
const OtherStack = createStackNavigator(OtherScreens, {
initialRouteName: 'TermsOfUse',
})
// App navigation
const AppContainer = createAppContainer(
createSwitchNavigator(
{
NotConnectedStack: NotConnectedStack,
ConnectedStack: ConnectedStack,
OthersStack: OthersStack,
},
{
initialRouteName: 'LandingStack',
defaultNavigationOptions: {
header: null,
headerMode: 'none',
},
}
)
)
export { AppContainer as default }
I can't use navigate.goBack() or navigation.navigate('Register') since
those screens are not in the same StackNavigator.
Not completely true, if your screen has a unique name, wherever you need to navigate to that page you can call the function this.props.navigation.navigate('SecondPage').
but sometimes going to an screen from another stack can't be done because it needs some data to be passed when navigating to. in this case MAKE SURE YOUR SCREEN HAS A DIFFERENT NAME
DevicesList: {screen: DevicesList },// this is wrong
DevicesListPage: {screen: DevicesList },// this is right
then you can navigate to that page like below from another stack:
this.props.navigation.navigate('DevicesListPage', {
//your data
});
I am having an issue when I navigate from Home component that contains a list of companies and I press in a button to load the Company view, the data is being loaded but when I press back in Android is returning to Home and when I press in a different company button to load its details, is rendering the same view with the same previous data, that means, the component is not being updated/unmounted.
These are my routes
const drawerConfig = {
initialRouteName: 'Home',
contentComponent: SideMenu,
drawerWidth: width,
}
const MainDrawerNavigator = createDrawerNavigator(
{
Home: {
screen: Home,
},
Company: {
screen: Company,
},
Gifts: {
screen: Gifts,
},
Contact: {
screen: Contact
}
},
drawerConfig,
);
const InitialStack = createStackNavigator(
{
Menu: {
screen: Menu,
path: 'menu/',
}
},
{
initialRouteName: 'Menu',
headerMode: 'none',
}
);
const SwitchNavigator = createSwitchNavigator(
{
Init: InitialStack,
App: MainDrawerNavigator,
},
{
initialRouteName: 'Init',
}
);
const AppContainer = createAppContainer(SwitchNavigator);
export default AppContainer;
I am navigating from Home to Company with this
goToCompany = company => event => {
this.props.navigation.navigate('Company', {
company,
});
}
And receiving the params in Company with this
componentWillMount() {
this.setState({ companyData: this.props.navigation.getParam('company', {}) });
}
So I am expecting the Company component will unmount on pop or allow me to change the state of the Company component when I send the details from Home.
I am using react-navigation 3.5.1 and react-native 0.59.3
React native navigation does not work as web. Read here for more details. https://reactnavigation.org/docs/en/navigation-lifecycle.html
When you navigat to other screen it doesn't actually get unmounted. Read documentation for details.
Use willFocus instead.
you can try using componentDidUpdate check in docs
componentDidUpdate(prevProps) {
// Typical usage (don't forget to compare props):
if (this.props.userID !== prevProps.userID) {
this.fetchData(this.props.userID);
}
}
You need to use the push method of navigation object. The push replace the current route with a new and the navigate search a route and if not exist create new one.
I have a react-native application whose top level App.js is as follows:
const AuthStack = createStackNavigator(
{ Landing, SignUpWithGoogle },
{
initialRouteName : 'Landing'
, navigationOptions : {
header : null
}
}
);
const AppStack = createStackNavigator(
{
AppContainer
, Campaign
, Compose
},
{
initialRouteName : 'AppContainer'
, navigationOptions : {
header : null
}
}
);
/**
#TODO:
force app to reload on user creation ...
there needs to be a state transition on user creation
... not sure how to
*/
class App extends React.Component {
render () {
const stack = (!this.props.authenticating && this.props.user)
? <AppStack {...this.props} />
: <AuthStack />
return (
<Loader
isLoaded = { !this.props.authenticating && this.props.feedIsLoaded}
imageSource = {logo}
backgroundStyle = {loading.loadingBackgroundStyle}
>
{stack}
</Loader>
)
}
}
There is a Loader component from https://github.com/TheSavior/react-native-mask-loader that hides the app with a splash page until the app has fetched user authentication data, or determined that this is a new user. This works great except in the case when the user signs up for the first time, then the app just jumps right into authenticated mode, and fails to load initial data that I want for the new user. The only to get around this is to restart the app, which is a no go. Is there a way to transition between AuthStack and AppStack better so that the information I want on signup are all there? One way would be to force reload the app so that we are directed back to the Loader screen and state, but it's unclear how this can be done.
I did something like this for my use case.
const Routes = {
Login: {
screen: Login
},
Status: {
screen: Status,
navigationOptions: {
gesturesEnabled: false, // To prevent swipeback
},
},
...
};
const LoggedRootStack = createStackNavigator(
{
...Routes
},
{
initialRouteName: 'Status'
}
)
const RootStack = createStackNavigator(
{
...Routes
},
{
initialRouteName: 'Login'
}
)
For passing props use Redux for keeping a global state. You can connect your components to redux state to access the props. Hope this helps
I have a very simple two tab app:
import React, { Component } from 'react';
import { AppRegistry } from 'react-native';
import { TabNavigator } from 'react-navigation';
import {
Sports,
News,
} from 'externalComponents';
const MyApp = TabNavigator({
Sports: { screen: Sports },
News: { screen: News },
});
AppRegistry.registerComponent('MyApp', () => MyApp);
The Sports and News components are provided by another company, and I cannot edit that code. If I load this into a TabBarIOS component, everything works fine and all tabs work as intended. However, with react-native-navigation and react-navigation, only the last tab loaded works properly.
Both the News and Sports components load a JSONDownloadService component like this:
downloadService = new JSONDownloadService(this);
And then it calls this:
downloadService.getJSON(this.state.url, type)
Now in JSONDownloadService because it has been passed the NEWS or SPORTS component in its constructor, it gets passed updateComponent (the part that is not getting called correctly). The getJSON() looks something like this:
getJSON(url, type) {
//set up vars...
fetch(request, init)
.then(function (response) {
// ...some code
})
.then(function (response) {
if (response) {
try {
// supposed to call `updateComponent` in News & Sports:
callback.updateComponent(response, type);
}
catch (err) {
console.log(err);
}
}
})
.catch(function (error) {
console.error(error);
});
}
The trouble is, updateComponent() is only ever called by the last component loaded in the tabBar. If I switch their positions, only the last one ever works. Except, if I comment out the code relating to JSONDownloadService in the last tab, THEN the first one works fine. It seems that whichever component last uses it prevents the rest from updating. How can I make this work using react-native-navigation or react-navigation?
Thanks in advance for any help!
It turns out, the reason TabBarIOS worked and react-navigation and react-native-navigation didn't was because the latter two load all the tabs at once. In this case it overloaded the JSONDownloadService component.
I was able to fix it in react-navigation at least using this code:
const MyApp = TabNavigator({
Sports: { screen: Sports },
News: { screen: News },
}, {
lazy: true, //used to be called "lazyLoad"
});
it just causes the app to lazily load the content for each tab.
I'm really new to React and I can't figure out how to render a "loading..." screen when a route is being loaded with getComponent. The getComponent call works fine and displays the component, but there's no indication on the UI that anything is happening between the request and the response. That's what I'm trying to figure out.
import Main from './pages/Main.jsx';
import Test from './pages/Test.jsx';
import Home from './pages/Home.jsx';
var Routes = {
path: "/",
component: Main,
indexRoute: {
component: Home
},
childRoutes: [
{
path: "test",
component: Test
},
{
path: "about",
getComponent: function(path, cb) {
require.ensure([], (require) => {
cb(null, require("./pages/about/About.jsx"));
});
}
}
]
};
export default Routes;
After trying to unsuccessfully force a "loading" component to display using onEnter or within the getComponent function, I thought maybe I should try using Redux to set a loading state to true/false and getting my main view component to display a loading screen:
import React from 'react';
import {connect} from 'react-redux';
import NavBar from '../components/Navigation/NavBar.jsx';
import Footer from '../components/Footer.jsx';
import Loading from './Loading.jsx';
import navItems from '../config/navItems.jsx';
import setLoading from '../actions/Loading.jsx';
var Main = React.createClass({
renderPage: function() {
if (this.props.loading) {
return (
<Loading/>
);
} else {
return this.props.children;
}
},
render: function() {
return (
<div>
<header id="main-header">
<NavBar navigation={navItems}/>
</header>
<section id="main-section">
{this.renderPage()}
</section>
<Footer id="main-footer" />
</div>
);
}
});
function mapStateToProps(state) {
return {
loading: state.loading
}
}
export default connect(mapStateToProps)(Main);
This seems to work if I manually set the loading state using an action, which is what I was looking to do. But (and I feel this is going to be a real noob question) I can't figure out how to access the store/dispatcher from within the router.
I'm not sure if I'm using the wrong search terms or whatever, but I'm completely out of ideas and every react-router/redux tutorial seems to skip over what I feel like has to be a common problem.
Can anyone point me in the right direction (and also let me know if what I'm doing is best practice?)?
EDIT: I'll try and clarify this a bit more. In the first code block, you can see that if I click a <Link to="/about"> element then the getComponent function will fire, which will lazy-load the About.jsx component. The problem I am having is I can't figure out how to show some sort of loading indicator/spinner that would appear immediately after clicking the link and then have it get replaced once the component loads.
MORE EDITING: I've tried creating a wrapper component for loading async routes and it seems to work, however it feels really hacky and I'm sure it isn't the right way to go about doing this. Routes code now looks like this:
import Main from './pages/Main.jsx';
import Test from './pages/Test.jsx';
import Home from './pages/Home.jsx';
import AsyncRoute from './pages/AsyncRoute.jsx';
var Routes = {
path: "/",
component: Main,
indexRoute: {
component: Home
},
childRoutes: [
{
path: "test",
component: Test
},
{
path: "about",
component: AsyncRoute("about")
}
]
};
export default Routes;
The AsyncRoute.jsx page looks like this:
import React from 'react';
function getRoute(route, component) {
switch(route) {
// add each route in here
case "about":
require.ensure([], (require) => {
component.Page = require("./about/About.jsx");
component.setState({loading: false});
});
break;
}
}
var AsyncRoute = function(route) {
return React.createClass({
getInitialState: function() {
return {
loading: true
}
},
componentWillMount: function() {
getRoute(route, this);
},
render: function() {
if (this.state.loading) {
return (
<div>Loading...</div>
);
} else {
return (
<this.Page/>
);
}
}
});
};
export default AsyncRoute;
If anyone has a better idea, please let me know.
I think I have this figured out. It may or may not be the correct way to go about things, but it seems to work. Also I don't know why I didn't think of this earlier.
First up, move my createStore code to its own file (store.jsx) so I can import it into the main entry point as well as into my Routes.jsx file:
import {createStore} from 'redux';
import rootReducer from '../reducers/Root.jsx';
var store = createStore(rootReducer);
export default store;
Root.jsx looks like this (it's an ugly mess, but I'm just trying to get something that works on a basic level and then I'll clean it up):
import {combineReducers} from 'redux';
import user from './User.jsx';
import test from './Test.jsx';
var loading = function(state = false, action) {
switch (action.type) {
case "load":
return true;
case "stop":
return false;
default:
return state;
}
};
export default combineReducers({
user,
test,
loading
});
I've made a basic component that shows Loading/Loaded depending on the Redux store's value of "loading":
import React from 'react';
import {connect} from 'react-redux';
var Loading = React.createClass({
render: function() {
if (this.props.loading) {
return (
<h1>Loading</h1>
);
} else {
return (
<h1>Loaded</h1>
);
}
}
});
export default connect(state => state)(Loading);
And now my Routes.jsx file looks like this (note I've imported the Redux store):
import Main from './pages/Main.jsx';
import Test from './pages/Test.jsx';
import Home from './pages/Home.jsx';
import store from './config/store.jsx';
var Routes = {
path: "/",
component: Main,
indexRoute: {
component: Home
},
childRoutes: [
{
path: "test",
component: Test
},
{
path: "about",
getComponent: function(path, cb) {
store.dispatch({type: "load"})
require.ensure([], (require) => {
store.dispatch({type: "stop"});
cb(null, require("./pages/about/About.jsx"));
});
}
}
]
};
export default Routes;
This seems to work. As soon as a <Link/> is clicked to go to the /about route, an action is dispatched to set the "loading" state to true in the main store. That causes the <Loading/> component to update itself (I envision it would eventually render a spinner in the corner of the window or something like that). That weird require.ensure([]) function is run to get webpack to do its fancy code splitting, and once the component is loaded then another action is dispatched to set the loading state to false, and the component is rendered.
I'm still really new to React and while this seems to work, I'm not sure if it's the right way to do it. If anyone has a better way, please chime in!
Following the same approach as #David M I implemented a loading reducer and a function to wrap the dispatches.
Excluding the store creation and manage, they are basically as follows:
loadingReducer:
// ------------------------------------
// Constants
// ------------------------------------
export const LOADING = 'LOADING'
// ------------------------------------
// Actions
// ------------------------------------
const loadQueue = []
export const loading = loading => {
if (loading) {
loadQueue.push(true)
} else {
loadQueue.pop()
}
return {
type: LOADING,
payload: loadQueue.length > 0
}
}
export const actions = {
loading
}
// ------------------------------------
// Action Handlers
// ------------------------------------
const ACTION_HANDLERS = {
[LOADING]: (state, action) => (action.payload)
}
// ------------------------------------
// Reducer
// ------------------------------------
const initialState = false
export default function reducer (state = initialState, action) {
const handler = ACTION_HANDLERS[action.type]
return handler ? handler(state, action) : state
}
Notice how loadingQueue keeps the loading message active while there are remaining modules to fetch, for nested routes.
withLoader function:
import { loading } from 'loadingReducer'
const withLoader = (fn, store) => {
return (nextState, cb) => {
store.dispatch(loading(true))
fn(nextState, (err, cmp) => {
store.dispatch(loading(false))
cb(err, cmp)
})
}
}
export default withLoader
Now when defining new routes we can dispatch the loading action implicitly using withLoader:
someRoute:
import withLoader from 'withLoader'
import store from 'store'
const route = {
path: 'mypath',
getComponent: withLoader((nextState, cb) => {
require.ensure([], require => {
cb(null, require('something').default)
}, 'NamedBundle')
}, store)
}
export default route
OK, let's see if I can shed some light on this here:
I can't figure out how to access the store/dispatcher from within the router
There is no need to do that AFAIK. You can specify all routes, listing the components that should answer each route (like you did above), and then connect each of the components to the redux store. For connecting, your mapStateToProps function can be written in a much simpler fashion, like this:
export default connect(state => state)(Main);
Regarding the loading state: I think it is a step in the wrong direction to have a slow-loading component and to display a waiting indicator while it is loading. I would rather have a fast-loading component that loads all of its data asynchronously from the backend, and while the data is not yet available, the component renders a waiting indicator. Once the data is available, it can be displayed. That is basically what you sketched in your second edit.
It would be even better if you could drive this off of your actual data, i.e. no data present -> show the loading screen / data present -> show the real screen. This way, you avoid issues in case your loading flag gets out of sync. (More technically speaking: Avoid redundancy.)
So, instead of making the wrapper generic, I would rather create a standalone component for the loading screen and display that whenever each individual component feels the need for it. (These needs are different, so it seems to be difficult to handle this in a generic way.) Something like this:
var Page = function(route) {
return React.createClass({
getInitialState: function() {
// kick off async loading here
},
render: function() {
if (!this.props.myRequiredData) {
return (
<Loading />
);
} else {
return (
// display this.props.myRequiredData
);
}
}
});
};
dynamic load async routers are using require.ensure, which use jsonp to download scripts from network.
because of slow networking, sometime, UI blocks, the screen is still showing the previews react component.
#Nicole , the really slow is not the data loading inside component, but is the component self, because of jsonp