What is the difference between React-router BrowserRouter and HashRouter?
Tell me, what is the difference between BrowserRouter and HashRouter? And in which cases is it better to use this or that option?
1 answers
Short answer:
Both of them will create a special history object. You should use BrowserRouter
if you have a server that responds to requests, and HashRouter
if you use a static file server like GithubPages
Detailed response:
BrowserRouter
Uses the Browser history API (popstate
, replaceState
as well as methods pushState
) also does not support older browsers (IE 9 and below)
<BrowserRouter
basename={optionalString}
forceRefresh={optionalBool}
getUserConfirmation={optionalFunc}
keyLength={optionalNumber}
>
<App />
</BrowserRouter>
basename
- The base path for all locations.
Example:
<BrowserRouter basename="/technologies">
<Link to="/js"/> // рендерит <a href="/technologies/js">
<Link to="/python"/> // рендерит <a href="/technologies/python">
</BrowserRouter>
getUserConfirmation
- The function is used to confirm navigation.You can use this option when you have <MemoryRouter>
directly with <Prompt>
.
Roughly speaking, when it is not necessary to let the user go from the page (for example, the form began to fill out and threw)
forceRefresh
- If the value is true
router
it will completely refresh the pages every time you click on them.
keyLength
- Specifies how long the location.key
property should be, the default value is 6. (Maximum of 11 characters although this is not written in the documentation)
HashRouter
Uses hash
in URL
( window.location.hash
) for manipulating routes
<HashRouter
basename={optionalString}
getUserConfirmation={optionalFunc}
hashType={optionalString}
>
<App />
</HashRouter>
hashType
- The encoding type to use in window.location.hash
.Available values slash
, noslash
and hashbang
.
-
slash
- Creates a hash like#/
also#/main/profile
-
noslash
- Creates a hash like#
also#main/profile
-
hashbang
- The third option is outdated and not supported by Google-I do not use and do not advise
The answer has been updated, but I will leave my old answer also here (below), maybe someone will need it.
It's very simple.
For browser projects, there are BrowserRouter
and HashRouter
components. BrowserRouter
- should be used when you process dynamic requests on the server, and HashRouter
should be used when you have a static web website.
Here is an example:
If you upload a React project to github using BrowserRouter
and gh-pages
, it won't work.More precisely, the routes will not work.
Why?
Yes, because this is a static project and here you need to use HashRouter
an example of the project is here you can take a look .As you can see from the code, I use HashRouter
If your project involves using a backend, then use BrowserRouter