I understood that routing libraries for SPAs like https://github.com/ReactTraining/react-router help to parse the URL and put the app into a corresponding state of a state machine.
Is there more to routing than this?
Why is routing needed in the first place?
Why are URLs important? For example in a desktop app there are no URLs, so what's the big deal about them in a web app?
Routing is the mechanism by which requests (as specified by a URL and HTTP method) are routed to the code that handles them. As we've already noted, routing used to be file based and very simple: if you put the file foo/about. html on your website, you would access it from the browser with the path /foo/about. html.
Single-page application generally rely on a router. Routers are made up of routes, which describe the location that they should match. These can be static ( /about ) or dynamic ( /album/:id , where the value of :id can be any number of possibilities) paths.
There are two ways to support routing in single-page apps: Hashed URL Paths — We break the URL path with a # (Hash) so that the browser understands it's just a virtual fragment. Ordinary URL Paths (Non-Hashed URL Paths) — The server needs to intercept the request and return the index.
We simply couple a component with a specific route, which makes our root component (normally called App) clear, maintainable and readable. Without router, either the root component or state would be messy and hard to maintain.
I also have this problem: "Why do we need routing?". You can write apps without routing at all. The code can get messy but still, it is not impossible.
My biggest reason for having routing is because if the user hits the Back button of the browser (Forward button as well, for that matter), he will not be navigating within the app. The user might expect to navigate within the app using the history of the different "pages" he loaded previously. Instead, he will be thrown out of the web app. Hitting the Refresh button would also throw him to the root of the app.
From the user's point of view, it is a regular web app (he doesn't need to know how it is designed: SPA or otherwise) and it should work as any web app/website should work. Routing ensures this, doesn't it?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With