Yu Wu
Yu Wu

Reputation: 213

Can we include normal react component inside <Route />?

I want to do something like:

<Route>
    <MyComponent someCondition={true/false}>
        <Route1 />
        ....
    </MyComponent>
</Route

To handle some conditional rendering. However, <MyComponent /> seems not mounted upon rendering.

My question is: can we include normal react component within <Route>? If not, is there a better way to handle conditional routing?

Upvotes: 1

Views: 154

Answers (1)

Drew Schuster
Drew Schuster

Reputation: 2691

What exactly do you mean by conditional routing? Assuming you mean something like not letting a user hit a route if they aren't authenticated, you can use react-router's onEnter hooks . You can make a parent <Route> that doesn't have a component prop and just handles routing checks. I used some simple onEnter checks in this example.

// onEnter hooks for login and home page to redirect if necessary
const checkAuth = function (nextState, replace) {
  const { user } = store.getState()
  if (isEmpty(user)) {
    replace('/')
  }
}
const checkSkipAuth = function (nextState, replace) {
  const { user } = store.getState()
  if (!isEmpty(user)) {
    replace('/home')
  }
}

var Index = () => {
  return (
    <Provider store={store}>
      <Router history={history}>
        <Route path='/' component={Container}>
          <IndexRoute component={Login} onEnter={checkSkipAuth} />
          <Route path='home' component={Home} onEnter={checkAuth} />
          <Route path='*' component={NoMatch} />
        </Route>
      </Router>
    </Provider>
  )
}

Upvotes: 3

Related Questions