How to push to History in React Router v4?


When you use the <BrowserRouter> , <HashRouter> , <MemoryRouter> , and <NativeRouter> , a history object will be created for you. This is convenient, and the history object is readily accessible from within your React components, but it can be a pain to use it outside of them. If you need to access a history object outside of your components, you will need to create your own history object (in its own module) and import it throughout your project.

If you do this, make sure that you use the generic <Router> component and not one of the specialty routers.

 // history.js
import { createBrowserHistory } from 'history'
export default createBrowserHistory()

// index.js
import { Router } from 'react-router-dom';
import history from './history'
  <Router history={history}>
    <App />
), document.getElementById('root'))

// nav.js
import history from './history'

export default function nav(loc) {