Removing # from HashRouter
Due to the front end nature of your client side React application, routing is a bit of a hack. The functionality of the two main router options are as follows :
HashRouter
uses a hash symbol in the URL, which has the effect of all subsequent URL path content being ignored in the server request (ie you send "www.mywebsite.com/#/person/john" the server gets "www.mywebsite.com". As a result the server will return the pre #
URL response, and then the post #
path will be handled by parsed by your client side react application.
BrowserRouter
will not append the #
symbol to your URL, however will create issues when you try to link to a page or reload a page. If the explicit route exists in your client react app, but not on your server, reloading and linking(anything that hits the server directly) will return 404 not found errors.
The solution to this problem can be seen on this extensive post : https://stackoverflow.com/a/36623117/2249933
The main principle is that you match your client side routes, with routes on your server, that way allowing clean url's, but without the limitations of browser router on it's own.
juaoregon
Front-end developer at EF Zurich. Learning React, Polymer and Angular!
Updated on June 15, 2022Comments
-
juaoregon almost 2 years
I'm using
react-router-dom
for my routing and, since I'm also using GitHub Pages, I need to useHashRouter
in myRouter.jsx
like soimport React from 'react'; import { HashRouter as Router, Route, Switch } from 'react-router-dom'; import Home from './Home'; import Customer from './Customer'; const MyRouter = () => ( <Router> <Switch> <Route path="/customer" component={Customer} /> <Route path="/" component={Home} /> </Switch> </Router> ); export default MyRouter;
In my
Home.jsx
component I have defined my propTypes like soHomepage.propTypes = { history: PropTypes.shape({ // set by react-router push: PropTypes.func.isRequired, }).isRequired, };
My problem is that everytime I get a
#
in my URL and I would like to know why is it there all the time and why does my localhost without#
redirect me to the same URL but with#
(like if I go to http://localhost:4000/myApp/ it will redirect me to http://localhost:4000/myApp/#/). I would like to get rif of it for tracking purposes. I've tried usingBrowserRouter
but it won't work, as well as the history parameter for the Router likehistory={createHashHistory({ queryKey: false })}
orhistory={browserHistory}
.Thank you very much (and sorry for my English)
-
juaoregon about 6 yearsIf I use
BrowserRouter
I have this problem: My homepage is localhost:4000/myRepo/myApp/en and then if I click on any customer link it will take me to localhost:4000/customer1 (e.g.) -
Tyler Sebastian about 6 yearsyou need to set the base path using the
basename
prop - it sounds like, in your case, you needbasename="/myRepo/myApp/en"