With react-router
I can use the Link
element to create links which are natively handled by react router.
I see internally it calls t
For React Router v4+
Assuming that you won't be needing to navigate during the initial render itself (for which you can use
component), this is what we are doing in our app.
Define an empty route which returns null, this will allow you to get the access to the history object. You need to do this at the top level where your Router
is defined.
Now you can do all the things that can be done on history like history.push()
, history.replace()
, history.go(-1)
etc!
import React from 'react';
import { HashRouter, Route } from 'react-router-dom';
let routeHistory = null;
export function navigateTo(path) {
if(routeHistory !== null) {
routeHistory.push(path);
}
}
export default function App(props) {
return (
{
routeHistory = history;
return null;
}}
/>
{/* Rest of the App */}
);
}