Monaca Onsen UI Discord Chat Github Repo

Implement authentication with page redirect Onsen UI 2 & React



  • While migrating our Onsen v1 app (based on AngularJS1) to Onsen v2 with React, I bumped into a little problem: implementing logic regarding user authentication (redirecting to login screen if there are no “saved credentials”)

    Here’s how my app is structured…

    Entry point is the App.js file, which looks like this:

    import React from 'react';
    
    import {Navigator} from 'react-onsenui';
    
    import Home from './Home';
    import Login from './Login';
    
    class App extends React.Component {
    
        renderPage(route, navigator) {
            route.props = route.props || {};
            route.props.key = route.comp.displayName;
            route.props.navigator = navigator;
            return React.createElement(route.comp, route.props);
        }
    
        render() {
            return (
                <Navigator
                    initialRoute={{comp: Home}}
                    renderPage={this.renderPage}
                />
            );
        }
    }
    
    export default App;
    

    You can see that I have my references for both ‘Home’ and ‘Login’ components, however, I want to decide which component to render.

    I tried the following: use ‘Home’ as the initialRoute, and decide in the Home components constructor if we need to go to the Login page.

    constructor(props) {
        super(props);
        this.state = {
            isOpen: false
        };
        const authenticated = GetAuthenticated();
        if(!authenticated) {
           this.props.navigator.pushPage({comp: Login});
        }
    }
    

    This simply did not work, the Login page was never shown.

    So basically, what I would like to do is to look in the localStorage for user credentials (or any other place for storing these kind of information), and based on this decide whether to load up the ‘Home’ page or the ‘Login’ page.