You use the history
prop. You can read about it here: https://reacttraining.com/react-router/web/api/history
Essentially you wrap your component in the withRouter
HOC, and it will pass the history
prop to your component which you'll see here: https://reacttraining.com/react-router/web/api/withRouter. It blends very well with React Recompose. I modified the "basic example" of the react router docs as an example here of using withRouter with the history
prop
// create-react-app test && cd test && npm i && npm install react-router-dom
// replace contents of App.js then `npm run start`
import React, { Component } from 'react';
import { withRouter } from 'react-router'
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom'
class BasicExample extends Component {
render() {
return(
<Router>
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
</ul>
<hr/>
<Route exact path="/" component={withRouter(Home)}/>
<Route path="/about" component={About}/>
</div>
</Router>
)
}
}
class Home extends Component {
render() {
const {history} = this.props;
const handleClick = (e) => {
history.push("/about")
}
console.log(history)
return (
<div>
<h2>Home</h2>
<button onClick={handleClick}>To about</button>
</div>
)
}
}
const About = () => (
<div>
<h2>About</h2>
</div>
)
export default BasicExample;
If you're creating the link in your JSX, use the Link
component, which looks like this
<Link to="/">...</Link>
If you're doing it inside of your PrivateRoute
component, I think what you want is something more like the Redirect
component: https://reacttraining.com/react-router/web/api/Redirect
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props => (
props.isAuthorized ? (
<Component {...props}/>
) : (
<Redirect to={{
pathname: '/',
state: { from: props.location }
}}/>
)
)}/>)