Normally, we use react-router-dom
library in order to navigate to each page.
The usage is normally just like following and it is the same as what created by create-react-app
.
history.js
file
import * as history from 'history';
export default history.createBrowserHistory();
index.js
file
import {Router} from 'react-router-dom';
import history from '../history';
<Router history={history}></Router>
But I don't understand why history
is necessary for the Router
.
Is there anyone who can lend a hand to make me understand?
Router
is a low level interface for other routers such as BrowserRouter and HashRouter etc. So, if you are using Router
, you must provide history
object as it doesn't have its own.
But, if you don't want to provide your own history object, you can use BrowserRouter
. It has its own history
object.
See BrowserRouter and Router.
From docs:
Router: The common low-level interface for all router components. Typically apps will use one of the high-level routers instead:
<BrowserRouter>
,<HashRouter>
,<MemoryRouter>
,<NativeRouter>
or<StaticRouter>
Here is how to import these:
import { Router } from "react-router-dom"
import { BrowserRouter } from "react-router-dom"
We can also use an alias to import BrowserRouter:
import { BrowserRouter as Router } from "react-router-dom"
// Now Router is still a BrowserRouter
// Probably this causes the confusion
One common reason or benefit of using low level Router
with your own history
is that, this way, you can import and use history
in any JS file (not only in a React Component).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With