How to Create a Simple JavaScript Router?

Estimated read time 1 min read

Here’s a simple example of how you could create a router in JavaScript:

const routes = {};

function addRoute(path, callback) {
  routes[path] = callback;
}

function navigateTo(path) {
  if (routes[path]) {
    routes[path]();
  } else {
    console.error(`Route not found: ${path}`);
  }
}

// Example usage:
addRoute("/home", () => {
  console.log("You are now on the home page.");
});

addRoute("/about", () => {
  console.log("You are now on the about page.");
});

navigateTo("/home");
// Output: You are now on the home page.

navigateTo("/about");
// Output: You are now on the about page.

navigateTo("/contact");
// Output: Route not found: /contact

This example demonstrates the basic steps to create a router:

  1. Create an object to store the routes.
  2. Write a function to add a new route to the router.
  3. Write a function to navigate to a specific route.
  4. Call the functions to add routes and navigate to them.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply