How to add hash to urls in react router 4

I want to add a hash to my endopints in react-router to prevent error responses from the server. I am using python -m SimpleHTTPServer -p 8888

to create a server.

This short example works, but when I try to reload the page on some route, for example /about

, I get the 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 />          
        );
    }
}

      

+3


source to share


1 answer


There are two ways to get around this:

1) Make your web server always respond with the same file index.html

, regardless of the route. This will prevent 404 errors, but not ideal as it doesn't support browser caching.



2) Use a HashRouter - it will maintain the UI route in the hash portion of the url, which should not force the server to return 404 and will allow browser side cache to be used. The downside to this approach is that you cannot use #target links for specific parts of the webpage.

+8


source







All Articles