Sign in
Log inSign up

Reactjs conditional routing using navlink

jim toby's photo
jim toby
·Nov 3, 2018

I have a sign in button that is supposed to direct users to a welcome page if and only if they are authenticated.

This is my App class that controls the routing.

import React, {Component} from 'react';
import {BrowserRouter, Route, Switch} from 'react-router-dom';
import SignIn from './ScreenViews/SignIn'
import Welcome from './ScreenViews/Welcome'

class App extends Component {

    render() {
        return(

            <BrowserRouter>
                <Switch>
                    <Route path= "/signin" component={SignIn}/>
                    <Route path= "/welcome" component={Welcome}/>
                </Switch>
            </BrowserRouter>

        )
    }
}
export default App;

Inside of my SignIn class, I have a sign in button that is wrapped with NavLink tag like this:

<NavLink to = "./welcome">
    <Button submit primary>
        Login
    </Button>
</NavLink>

This component is wrapped in a form, so when users click login, a callback function is called and in that function I make a post request and I only want to allow users to direct to the welcome page if I get a valid response. The On submit function looks like this:

handleSubmit = event => {
    const { email, password } = this.state;
    axios.post('/api/authenticate', {
      email: email,
      password: password
    })
    .then(function (response) {
        //If we are here, users should be allowed to direct to welcome page
    })
    .catch(function (error) {
      console.log("We are getting this error:")
      console.log(error.response);
    });
}

How can I make it so that users get directed to the welcome page if and only if I get a response. Right now, it directs to the page regardless. I looked in to installing history from npm using npm install history and pushing "/welcome" to the history when users are authenticated but I'm not sure if that's what's best.