Fix React Router URL’s issue with HashRouter

Have you ever faced a blank page or a 404 error while refreshing a page in your app with React Router? The issue occurs when the expected URL doesn’t match with your app routes.

You can resolve this issue using the HashRouter. The Hash Router uses the hash portion of the URLs (everything after the # symbol) that keep track of the location with the SPA (Singel Page Application) app.

Here is a basic example of How to switch from the BrowserRouter to the HashRouter in your React app.

import React from 'react';
import { HashRouter as Router, Route, Link } from 'react-router-dom';

function App() {
  return (
    <Router>
      <nav>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/about">About</Link>
          </li>
        </ul>
      </nav>

      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
    </Router>
  );
}

function Home() {
  return <h2>Home</h2>;
}

function About() {
  return <h2>About</h2>;
}

export default App;
With the HashRouter, Your URLs will look like http://localhost:3000/#/about rather than http://localhost:3000/about.

So if you refresh the page or manually add a URL the request will go to the server. Then it returns the same HTML and JavaScript. Now the router uses the hash value to determine the correct page location within the React app.

Result:

Hash value in the URL may not be as visually appealing as a traditional URL without a hash. But this is a cosmetic issue that doesn’t affect the functionality of your app.