Reputation: 5513
How can I push a route to history conditionally using react router 4? I get the error 'history.push is not a function'.
I am not looking for a redirect, but something with which the back button in the browser also works.
import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter, Switch, Route, Redirect} from 'react-router-dom';
import Signup from './components/Signup';
import Welcome from './components/Welcome';
class App extends React.Component {
constructor() {
super();
this.state = {
isLoggedIn: false
};
}
render() {
return (
<BrowserRouter>
<div>
<Route exact path="/signup" component={Signup}/>
<Route exact path="/welcome" component={Welcome}/>
<Route exact path="/" render={() => (
this.state.isLoggedIn ?
history.push('/welcome') : history.push('/signup')
)}/>
<Redirect to="/"/>
</div>
</BrowserRouter>
);
}
}
ReactDOM.render(<App/>, document.getElementById('root'));
Upvotes: 0
Views: 1283
Reputation: 7777
There is an option on the Redirect component to do exactly what you want.
<Redirect to="/" push />
Will do the navigation, and also push onto the browser history
history.push
always felt wrong to me :)
Upvotes: 2