I would like to add hash to my endopints in react-router for preventing error responses from server. I'm using python -m SimpleHTTPServer -p 8888
for creating server.
This short example works but when I'm trying reload page on some route like /about
then I get an error: Error response Error code 404. Message: File not found. Error code explanation: 404 = Nothing matches the given URI.
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
const Routes = () => (
<Router>
<div>
<ul>
<li><Link to="/about">About Link</Link></li>
<li><Link to="/company">Company Link</Link></li>
</ul>
<Switch>
<Route path="/about" component={About} />
<Route path="/company" component={Company} />
</Switch>
</div>
</Router>
);
class App extends React.Component {
render() {
return (
<Routes />
);
}
}
To get query parameters from a hash fragment with React Router v5, we can use the useLocation hook to return the location object and use the location. hash property to get the hash part of the URL. We have the Foo component that calls the useLocation and assign the returned object to the location variable.
BrowserRouter: BrowserRouter is a router implementation that uses the HTML5 history API(pushState, replaceState and the popstate event) to keep your UI in sync with the URL. It is the parent component that is used to store all of the other components.
HashRouter: When we have small client side applications which doesn't need backend we can use HashRouter because when we use hashes in the URL/location bar browser doesn't make a server request. BrowserRouter: When we have big production-ready applications which serve backend, it is recommended to use <BrowserRouter> .
There are two ways to go around it:
1) Make your web server respond always with the same index.html
file, no matter the route. This will prevent the 404 errors, but is not perfect as it won't support browser caching
2) Use HashRouter - it will keep the UI route in hash part of the URL, which should not make the server return 404 and will enable browser-side cache. The downside of this approach is that you can't use #target links to specific parts of the webpage
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