To create a URL router in JavaScript, you can use the History API and the window.onpopstate event to detect changes in the URL and update the content of your Single Page Application (SPA) accordingly.
Here's a basic example of how to create a router:
index.tsx823 chars34 lines
In this example, we define our routes as an object where the keys are the URLs and the values are the corresponding content we want to render. We then create a function renderContent
that looks up the current URL in the routes
object and updates the content of our app. We use the window.onpopstate
event to call the renderContent
function whenever the URL changes.
We also create a function navigateTo
that takes a URL as a parameter, updates the URL using window.history.pushState
, and calls the renderContent
function.
Finally, we add an event listener to the document that listens for link clicks and prevents the default behavior of navigating to a new page. Instead, we call the navigateTo
function with the new URL.
This is a simple example of a URL router in JavaScript. You can customize it to fit your specific needs and add more advanced features like nested routes and route parameters.
gistlibby LogSnag