What is the difference between HashRouter and BrowserRouter in React?
Answer a question
I am new to programming which makes things slightly difficult for me to understand if I read the official docs.
I was reading about React Router 4 from here
In this article, the author was talking about <HashRouter> and <BrowserRouter>
This is what he mentioned:
HashRouter basically it uses the hash in the URL to render the component. Since I was building a static one-page website, I needed to use this.
BrowserRouter, it uses HTML5 history API to render the component. The history can be modified via pushState and replaceState. More information can be found here
Now, I don't get the significance and use cases for both, Like what does he mean when he says history can be modified via pushState and replaceState and it uses the hash in the URL to render the component
While the first explanation for BrowserRouter is entirely vague to me, the second explanation about HashRouter also doesn't make sense, like why would someone use Hash (#) in the url to render the component?
Answers
BrowserRouter
It uses history API, i.e. it's unavailable for legacy browsers (IE 9 and lower and contemporaries). Client-side React application is able to maintain clean routes like example.com/react/route but needs to be backed by web server. Usually this means that web server should be configured for single-page application, i.e. same index.html is served for /react/route path or any other route on server side. On client side, window.location.pathname is parsed by React router. React router renders a component that it was configured to render for /react/route.
Additionally, the setup may involve server-side rendering, index.html may contain rendered components or data that are specific to current route.
HashRouter
It uses URL hash, it puts no limitations on supported browsers or web server. Server-side routing is independent from client-side routing.
Backward-compatible single-page application can use it as example.com/#/react/route. The setup cannot be backed up by server-side rendering because it's / path that is served on server side, #/react/route URL hash cannot be read from server side. On client side, window.location.hash is parsed by React router. React router renders a component that it was configured to render for /react/route, similarly to BrowserRouter.
Most importantly, HashRouter use cases aren't limited to SPA. A website may have legacy or search engine-friendly server-side routing, while React application may be a widget that maintains its state in URL like example.com/server/side/route#/react/route. Some page that contains React application is served on server side for /server/side/route, then on client side React router renders a component that it was configured to render for /react/route, similarly to previous scenario.
更多推荐
所有评论(0)