How can I redirect before render?

Viewed 7667

I'm trying to build an web app using react and I kind of hit the wall.

The thing is, I don't want any users who has already logged in to access the login page.

I tried to redirect them using render method and componentDidMount method, but since the render method is called before componentDidMount, the login page flashes out before redirection.

These are my codes.

I'm using redux and firebase to control the component state and authenticate.

class CenterPanel extends Component {
    render() {
        const { user }=this.props;

        if(user!=null) { //this is how I tried to redirect
            return ( //
                <Redirect to='/somewhereNotHere' />
            );
        }

        return ( //this flashes out before redirection
            <div className={cx('center_panel')}>
                <div className={cx('button')}>
                    login
                </div>
            </div>
        );
    }

    componentDidMount() {
        const { changeUserStatus }=this.props;

        firebase.auth().onAuthStateChanged(
            (user) => changeUserStatus(user)
        );
    }
}

would appreciate any kind of advice. Thx in advance.

3 Answers

Maybe the props user is undefined before you call onAuthStateChanged

If it is right, you can control your component by three user values. undefined, null, user value.

render() {
        const { user }=this.props;

        if(user === undefined){
            return null; //or Loading component
        }

        if(user!=null) { //this is how I tried to redirect
            return ( //
                <Redirect to='/somewhereNotHere' />
            );
        }

        return ( //this flashes out before redirection
            <div className={cx('center_panel')}>
                <div className={cx('button')}>
                    login
                </div>
            </div>
        );
    }

You should try this,

if(user && user!==null) { //this is how I tried to redirect
     return <Redirect to='/somewhereNotHere' />  //Make sure you have imported Redirect from correct package i.e. react-router-dom
}else{
     return ( //this flashes out before redirection
            <div className={cx('center_panel')}>
                <div className={cx('button')}>
                    login
                </div>
            </div>
     );
}

Another way of doing this is in Routes itself,

<Route exact path="/your_Path_to_component" render={() => (
  user ? ( //get the user data as you are passing as props to CenterPanel component
    <Redirect to="/somewhereNotHere"/>
  ) : (
    <CenterPanel />
  )
)}/>

In this way no need to pass user as props to CenterPanel component as well as no need to write any redirection logic in CenterPanel component.

you can solve it by conditioning the view

user && <div>...</div>

the content of the page will only show up if the user is truthy (authenticated).

Related