Routing
Series: Building an e-commerce frontend with Tweakwise
This article is part of a series where weโll walk you through building a robust e-commerce platform using Tweakwise, using industry best practises.
Behind every good lister page is a good router. And behind every router is a URL.
It is recommended to use the page URL for state management of the lister page. By using the URL to store and manage the filters, sorting options, and pagination, ensures the application state is shareable and bookmarkable. It also creates opportunities to make the URL SEO friendly.
To implement state management through routing, follow these steps:
- Set-up routes:
Use a router (e.g., react-router for React, vue-router for Vue, or Next.js's routing) to define paths for your application. Each route can represent a different state or view of your lister page (e.g., /products/clothing/?page=2).
Dynamically append query parameters to capture the state, such as filters, sort option, or page numbers. Consider using clean SEO routes for some parameters (e.g. /products/clothing/color-red/).
- Sync UI state with URL:
Replace local state management (like useState or Vue's data) with the URL's query parameters. For example, updating the filter state updates the URL with ?tn_fk_color=red.
- Fetch data based on URL parameters:
Parse the URL parameters in your application to fetch the corresponding data. For instance, in React, use useSearchParams or useRouter in Next.js to read and react to changes in query parameters.
- Maintain History:
Use routing features like history.pushState (React or Vue history mode) to allow users to navigate back and forth while preserving state.
- Server-Side rendering compatibility:
For frameworks like Next.js, ensure the state is properly fetched and rendered server-side to support SEO.
Examples
React
Use react-router to manage routes and useSearchParams for reading query strings dynamically. FreeCodeCamp provides a detailed guide on this.
Vue
Combine vue-router with vuex-persist to create a robust state management solution. Define routes for different lister views and use for navigation.
Updated 3 days ago