AI Briefing
KO

Implementing a Hash Router Directly with Vanilla JS Without Libraries

·2022.12.06 09:00

Key point

This article introduces the process of building an SPA routing system using Fragment hashes and regular expressions without react-router-dom.

1 / 5

Details

This article covers how to implement a routing system directly with vanilla JS without relying on libraries like react-router-dom during SPA development. The goal is to help developers who find it difficult to customize or add methods when using libraries to deeply understand the principles of routing.

Fragment Hash-Based Routing

The two main methods for implementing routing without libraries are using Fragment hashes (hash router) and the history API (browser router). This article chose the Fragment hash method for broad browser support and simplified server configuration. Changing the hash does not trigger server requests or page refreshes, and it does not require separate server settings to prevent 404 errors.

Core Feature Implementation Steps

The router implementation centers on three core features: storing a list of routes, detecting URL changes and replacing content, and identifying parameters.

  • Route Mapping: The routes array is managed via a closure, and the addRoute method connects URLs with components.
  • URL Detection: The start method listens for the hashchange event to execute the component matching the current hash value.
  • Programmatic Navigation: Instead of <a> tags, clicking a button with the data-navigate attribute calls the navigate method to change the hash. Adding the location.replace option allows controlling page navigation without accumulating history.

Handling Path Parameters

Regular expressions are used to identify Path Parameters (e.g., :name, :song) within the URL. The :/\w+ pattern extracts parameter names, which are then replaced with a regular expression ([^\/]+) that matches the actual URL to support dynamic routing. The getUrlParams function passes the extracted parameter values (e.g., {name: 'IU', song: 'raindrop'}) to the corresponding component to render content dynamically.

This summary was generated automatically by AI. Check the original for the author's claims and context. Copyright belongs to the original author.

Our guide explains how the AI works. Report summary errors, attribution issues, or removal requests via Contact.