create a url router in javascript

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.tsx
// Define routes with their corresponding content
const routes = {
  '/': 'Home Page',
  '/about': 'About Us',
  '/contact': 'Contact Us',
};

// Render content based on current URL
const renderContent = () => {
  const url = window.location.pathname;
  const content = routes[url] || '404 Not Found';
  document.getElementById('app').textContent = content;
};

// Update content when URL changes
window.onpopstate = renderContent;

// Navigate to a new URL and update history
const navigateTo = (url) => {
  window.history.pushState(null, null, url);
  renderContent();
};

// Listen for link clicks and navigate to new URL
document.addEventListener('click', (event) => {
  if (event.target.matches('a')) {
    event.preventDefault();
    navigateTo(event.target.href);
  }
});

// Render initial content
renderContent();
823 chars
34 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