Reputation: 18859
Ok, I'm fed up trying.
The onEnter
method doesn't work. Any idea why is that?
// Authentication "before" filter
function requireAuth(nextState, replace){
console.log("called"); // => Is not triggered at all
if (!isLoggedIn()) {
replace({
pathname: '/front'
})
}
}
// Render the app
render(
<Provider store={store}>
<Router history={history}>
<App>
<Switch>
<Route path="/front" component={Front} />
<Route path="/home" component={Home} onEnter={requireAuth} />
<Route exact path="/" component={Home} onEnter={requireAuth} />
<Route path="*" component={NoMatch} />
</Switch>
</App>
</Router>
</Provider>,
document.getElementById("lf-app")
Edit:
The method is executed when I call onEnter={requireAuth()}
, but obviously that is not the purpose, and I also won't get the desired parameters.
Upvotes: 74
Views: 75569
Reputation: 630
For react-router-6
the Redirect
component has been replaced with Navigate
.
Below userState
will be either null or populated depending upon if user is logged in or not, can be your Redux state for example.
<Route path="/protectedRoute"
element={userState ? <protectedComponent/> : <Navigate to="/login"/>}/>
Upvotes: 1
Reputation: 6105
From react-router-v4 onEnter
, onUpdate
, and onLeave
is removed,
according the documentation on migrating from v2/v3 to v4:
on*
properties
React Router v3 providesonEnter
,onUpdate
, andonLeave
methods. These were essentially recreating React's lifecycle methods.With v4, you should use the lifecycle methods of the component rendered by a
<Route>
. Instead ofonEnter
, you would usecomponentDidMount
orcomponentWillMount
. Where you would useonUpdate
, you can usecomponentDidUpdate
orcomponentWillUpdate
(or possiblycomponentWillReceiveProps
).onLeave
can be replaced withcomponentWillUnmount
.
Upvotes: 34
Reputation: 6507
onEnter
no longer exists on react-router-4
. You should use <Route render={ ... } />
to get your desired functionality. I believe Redirect
example has your specific scenario. I modified it below to match yours.
<Route exact path="/home" render={() => (
isLoggedIn() ? (
<Redirect to="/front"/>
) : (
<Home />
)
)}/>
Upvotes: 136