Pierre Olivier Tran
Pierre Olivier Tran

Reputation: 955

React-router onEnter doesn't trigger

I'm setting up routes for a React app. When entering my Homepage, I'd like to log some data from Auth0. To do so, I'm simply user the onEnter attribute, but it seems like it doesn't work.

import React from 'react'
import {Route, IndexRedirect} from 'react-router'
import AuthService from 'utils/AuthService'
import Container from './Container'
import Home from './Home/Home'
import Login from './Login/Login'

[...]

const requireAuth = (nextState, replace) => {
  if (!auth.loggedIn()) {
    replace({ pathname: '/login' })
  }
}

const parseAuthHash = (nextState, replace) => {
  console.log('LOG SOMETHING YOU IDIOT');
  if (/access_token|id_token|error/.test(nextState.location.hash)) {
    auth.parseHash(nextState.location.hash)
  }
}

export const makeMainRoutes = () => {
  return (
    <Route path="/" component={Container} auth={auth}>
      <IndexRedirect to="/home" />
      <Route path="home" component={Home} onEnter={requireAuth} />
      <Route path="login" component={Login} onEnter={parseAuthHash} />
    </Route>
  )
}

export default makeMainRoutes

For some reason, when I'm on /login, nothing appears in console. I tried with alert too, doesn't trigger. Did I miss something ?

Upvotes: 0

Views: 462

Answers (1)

James Ganong
James Ganong

Reputation: 1171

I'm guessing you're using v4, which has done away with onEnter: https://reacttraining.com/react-router/web/api/Route

Instead, you are to use the render prop. Their new docs have an example of this: https://reacttraining.com/react-router/web/example/auth-workflow

Here's the main idea of it:

const PrivateRoute = ({ component, ...rest }) => (
  <Route {...rest} render={props => (
    fakeAuth.isAuthenticated ? (
      React.createElement(component, props)
    ) : (
      <Redirect to={{
        pathname: '/login',
        state: { from: props.location }
      }}/>
    )
  )}/>
)

Upvotes: 1

Related Questions