How to redirect to a specific page according to a condition in "react-router": "^4.0.0"
.
var { HashRouter, Route, Switch} = require('react-router-dom');
var {Provider} = require('react-redux');
firebase.auth().onAuthStateChanged((user) => {
if (user){
this.props.history.push('/todos/');
}else{
this.props.history.push('/');
}
});
store.dispatch(actions.startAddTodos());
ReactDOM.render(
<Provider store = {store}>
<div>
<HashRouter>
<div>
<div className="columns medium-6 large-4 small-centered">
<Switch>
<Route path='/todos' component={TodoApp}/>
<Route path='/login' component={Login}/>
<Route component={Login}/>
</Switch>
</div>
</div>
</HashRouter>
</div>
</Provider>,
document.getElementById('app')
);
Cannot read property 'props' of undefined
EDIT :
The Application on Github: React-Todo
You can't use
this.props
because you are not inside of a component.So to perform redirect you need to use the
Redirect
component fromreact-router-dom
I would recommend you create an HOC(High order component to take care of it.
Then you only need to import PrivateRoute inside of your index.js file instead of using
Route
usePrivateRoute
for the routes that require being authenticated.If you're using react router then it can be easier if you're maintaining user auth in your state.
Next, write a small wrapper for requireLogin in which you check the auth state and do redirection inside it. It looks something like this