Here's a reproducible example of how to programmatically change routes in the v4 reply router.
First install the template for a simple application:
sudo npm install -g create-react-app create-react-app demo-app cd demo-app npm install react-router-dom
Then we change /src/App.js to:
import React from 'react' import {BrowserRouter as Router, Route, Link, withRouter} from 'react-router-dom' const BasicExample = () => ( <Router> <div> <li><Link to="/">Home</Link></li> <li><Link to="/about">About</Link></li> <Route exact path="/" component={Home}/> <Route path="/about" component={About}/> </div> </Router> ) const Home = () => ( <div> <h2>Home</h2> </div> ) const Button = withRouter(({history}) => ( <button type='button' onClick={() => { history.push('/new-location') }}>Click Me!</button> )) const About = () => ( <div> <h2>About</h2> <Button /> </div> ) export default BasicExample
Then start your server:
npm run start
If you go to localhost: 3000, and then click "About", you will see the button component. Clicking on it will programmatically change the route to /new-location
duhaime
source share