Hash routing is a technique used in Single Page Applications (SPAs) to enable navigation through different views or components without reloading the entire page.

How does Hash Routing work?

It works by updating the URL in the address bar with a hash symbol (#) followed by a route, also known as a hash fragment.

When the route changes, the SPA can use JavaScript to update the content displayed on the page without performing a full page refresh.

Benefits of Hash Routing

There are several reasons why you might want to use hash routing in a SPA, such as:

Improved Performance

By only updating a small portion of the page rather than reloading the entire page, hash routing can improve the performance of your SPA.

This is especially important for applications with large or complex views that would take a long time to reload.

Better User Experience

Hash routing allows for a smooth, seamless transition between views or components, providing a better user experience.

That’s because the user does not need to wait for the entire page to reload each time they navigate to a new view.

Enhanced Browser History Management

Hash routing allows you to manipulate the browser’s history, allowing users to use the back and forward buttons to navigate through your SPA’s different views or components.

This can be especially useful in applications with a complex navigation structure or multiple content levels.

Adding Hash Routing to your React Application

You can take several approaches to implement hash routing in a React SPA.

One popular option is to use the react-router-dom library, which provides a declarative API for managing routing in your React app.

To set up a hash router in React using the react-router-dom library, you will need to follow these steps:

1. Install the react-router-dom Library

This can be done through either yarn or npm:

  • npm: npm install react-router-dom
  • yarn: yarn add react-router-dom

2. Import the HashRouter Component

The HashRouter component can be imported from react-router-dom , and you will need to wrap your root component with it.

It will handle all routing logic for your app:

import { HashRouter } from 'react-router-dom';

const App = () => {
  return (
    <HashRouter>
      <div>
        {/* Your app content goes here */}
      </div>
    </HashRouter>
  );
}

3. Define Your Routes Using the Route Component

The Route component takes two props: path, which specifies the URL path for the route, and component, which specifies the React component that should be rendered when the route is active:

import { Route } from 'react-router-dom';
import Home from './Home';
import About from './About';

const App = () => {
  return (
    <HashRouter>
      <div>
        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
      </div>
    </HashRouter>
  );
}

4. Add a Way for Users To Navigate Between Routes

This can be done using the Link component from react-router-dom, which creates a clickable element that will change the route when clicked:

import { Link } from 'react-router-dom';

function Navigation() {
  return (
    <nav>
      <ul>
        <li>
          <Link to="/">Home</Link>
        </li>
        <li>
          <Link to="/about">About</Link>
        </li>
      </ul>
    </nav>
  );
}

const App = () => {
  return (
    <HashRouter>
      <div>
        <Navigation />
        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
      </div>
    </HashRouter>
  );
};

5. (Optional) Use the Switch Component To Define a Default Route

This route will be rendered if no defined routes match the current URL.

This can be useful if you want to display a “404 not found” page or a similar message when the user navigates to an invalid route:

import { Switch } from 'react-router-dom';
import NotFound from './NotFound';

const App = () => {
  return (
    <HashRouter>
      <div>
        <Navigation />
        <Switch>
          <Route exact path="/" component={Home} />
          <Route path="/about" component={About} />
          <Route component={NotFound} />
        </Switch>
      </div>
    </HashRouter>
  );
};

Error handling and error routes management in React may be tricky to get right; that’s why we’ve written a definitive guide for it which you can check here.

Summary

In summary, hash routing is a useful technique for managing navigation in SPAs, allowing for faster and smoother transitions between views or components.

Using the react-router-dom library, you can easily set up a hash router in your React app and provide a better user experience.


Let me know your thoughts on this article by leaving a comment below!

Cheers!

👋 Hey, I'm Vlad Mihet
I'm Vlad Mihet, a blogger & Full-Stack Engineer who loves teaching others and helping small businesses develop and improve their technical solutions & digital presence.

💬 Leave a comment

Your email address will not be published. Required fields are marked *

We will never share your email with anyone else.