Chaitu
Chaitu

Reputation: 135

Auth based redirecting with react-router

I am new to React, In my project I've used react-router to define the routes. However, I have a same path to be redirected based on the condition. I tried putting conditonal operator as below but dint work, tired with if block as well.How to render different components with the same path based on a condition.

var Routes = (
    <Router history={hashHistory}>
        {role === undefined ? (
            <Route path='/' component={Login} />
            ):
            <Route path='/' component={Home}>
                <Route path='category' component={About}/>
                <Route path='input' component={Cate} />
                <Route path='charts' component={Chart}/>
                <Route path='buyerHome' component={customer}/>
            </Route>
        }
    </Router>
);

Upvotes: 2

Views: 4351

Answers (2)

Kokovin Vladislav
Kokovin Vladislav

Reputation: 10421

for redirect you can use onEnter

const checkRole = (nextState, replace)=>{
     if(role === undefined) replace('/login')
};

<Route path='/' component={Home} onEnter={checkRole}>
     <Route path='category' component={About}/>
      ...
</Route>
<Route path='/login' component={Login} />

or you may use HOC (High order component) to check role and other stuff

const CheckRole = Comp  => class extends React.Component{
    componentWillMount(){
        if(role===undefined) hashHistory.replace('/signup');
    }
    render(){
        return <Comp {...this.props}/>;
    }
};

<Route path='/' component={CheckRole(Home)}>
     <Route path='category' component={About}/>
     ...
</Route>
<Route path='/login' component={Login} />

if you prefer the same path for defferent components , on some condition base

<Route path="/" component={role===undefined ? Login : Home} />

if you use redux, then you may use redux-auth-wrapper. and it has some advantages over onEnter method.

Upvotes: 2

Tushar
Tushar

Reputation: 1123

You can use react-router onEnter hook to protect your route.

<Route path='/' component={Home} onEnter={requireAuth}>

function requireAuth(nextState, replace) {
  if (!role) {
    replace({
      pathname: '/login',
      state: { nextPathname: nextState.location.pathname }
    })
  }
}

Hope this helps.

Upvotes: 3

Related Questions