This content originally appeared on Bits and Pieces - Medium and was authored by Chameera Dulanga
A Modern React Router with Async Routing and More Features
React Location is a recently launched alternative library for React Router. As a React developer, I found it very interesting since it brings a new perspective to React routing.
In this article, I will discuss the features of React Location and compare it with React Router to give you a better understanding.
Introduction to React Location
React Location is a powerful client-side library recently introduced which allows you to implement routing. At first, it was introduced as a wrapper for the react Router v6 beta release. But, now, React Location can be recognized as a solid alternative to React Router library since it provides unique features like;
- Synchronous route elements.
- Data loaders.
- Search param APIs.
- Nested routing.
- Code-splitting.
Apart from that, React Location supports almost all the features of React Router, and allows to extend its features via plugins.
Installing React Location
Installing React Location is pretty straightforward. You can treat it like any other JavaScript library and install it using NPM or Yarn.
// NPM
npm install react-location --save
// Yarn
yarn add react-location
// Usage
import {ReactLocation,Router,useMatch} from "react-location";
Basics of React Location
If you have previously worked with React Router, working with React Location is quite similar. However, it would be better to get some basic understanding of React Location to master it further.
1. Router Component
React Location provides a component named Router as the root provider component for ReactLocation instance. It is responsible for handling all the routing configurations of your application.
The above example shows how to use React Location Router without any child props. However, if you want to use child props, you need to add <Outlet /> to render the routes.
2. Defining Routes with React Location
React Location route definition is pretty similar to React Router.
It considers routes as array objects, and each object can contain more routes as child arrays. However, there are several rules you need to follow when defining routes with React Location.
Important rules to follow when defining routes with React Location
- Routes are matched in the order they are specified.
- If you don't define a path to a route, the default path will be path: *
- If you don't define an element to a route, the default element will be element: <Outlet />
- If index routes (/)do not have children, they will be considered exact.
- Param'd routes, wildcard routes, and routes without paths will always match when encountered.
- No search params will always match.
Also, React Location supports code splitting and async data loading with routes.
The below code snippet shows how to use React Location to retrieve article data using the route parameters.
You can find more information about code splitting and async data loading in their documentation.
3. Internal Navigations using React Location
React Location provides a component named Link for internal navigations. For example, if you create a navigation bar, you can use Link components to handle it’s navigations.
These components work flawlessly with other usual browser functions like open in new tab, ctrl + left click, and open in new window. Also, you can update pathnames, search parameters, and hashes using Link components.
4. Navigate Component in React Location
We can use Navigate component similar to the Link component. However, they are used for declaratively and relatively navigating to any route instead of generating internal navigations links.
function App () {
return <Navigate to='./about'>
}
Besides, React Location also provides a Hook called useNavigation for the same purpose. I will explain it more in the next section.
5. Using Hooks in React Location
React Location library provides a set of Hooks to manage routes easily. So, let's see what the functionalities of these Hooks are and how we can use them.
useMatch and useMatches
useMatch and useMatches Hooks return the nearest route match within the context it was called. Thus, they can access route data, route params, and the next child match in a route.
The only difference between them is that useMatch returns only 1 match while useMatches returns all the route matches within the context.
useNavigate
useNavigate Hook allows you to programmatically navigate your application.
usePrompt
usePrompt Hook can be used to create prompt dialogs. It takes 2 input parameters as message and when.
- message — String which is displayed as the prompt message.
- when — Boolean, which defines the condition of the prompt display.
export function usePrompt(
message: string,
when: boolean | any
): void
In addition to the above discussed 4 main Hooks, React Location supports 4 more Hooks named useSearch, useMatchRoute, useRouter and useResolvePath. You can find more details about them in the documentation.
6. Plugins Support for React Location
Since React Location is a relatively new library, some of its features are still developing. However, we can use several 3rd party plugins with React Location to fill those gaps.
Ranked Routes
Ranking routes can be really useful to avoid confusion between route selection. For example, if we consider the React Router, by default, it will rank the routes according to the number of segments and mick the most matching route.
But, React Location doesn't provide inbuilt support for that, and you have to use a 3rd party plugin called react-location-rank-routes and manually implement this feature.
All you need to do is install react-location-rank-routes using NPM and include it as the filterRoutes option in the Router component.
// NPM
npm i react-location-rank-routes
// Yarn
yarn add react-location-rank-routes
// Usage
<Router
location={location}
filterRoutes={rankRoutes}
routes={[
...
]}
/>
Caching for Loaders
Previously, I mentioned that we could use React Location to load data from API endpoints asynchronously. But, that's not all. React Location supports a plugin called react-location-simple-cache which can be used to create a cache for route loaders.
You can easily install it using NPM or Yarn and start caching your data from the route file itself.
// NPM
npm i react-location-simple-cache
// Rarn
yarn add react-location-simple-cache
// Usage
import { ReactLocationSimpleCache } from 'react-location-simple-cache'
<Router
{
path: ':articleId',
element: <Article />,
loader: routeCache.createLoader( async ({ params }) => ({
article: await getArticlesById(params.articleId),
})),
}
/>
Also, react-location-simple-cache library provides a set of functions to read, find and clear cached items.
- cache.clearAll — Clears the cache.
- cache.find — returns the first matching record.
- cache.invalidate — Invalidates cache items.
- cache.filter — Filter and returns records.
In addition to these 2 plugins, there are other plugins like react-location-jsurl and react-location-elements-to-routes that can improve the developer experience of React Location.
React Location vs React Router
React Location is an excellent alternative for React Router. However, They both have some common features as well as several differences.
So, I thought comparing the core features of these 2 libraries using the chart below would give you a clear understanding of their similarities and differences.
Build better Component Libs and Design Systems
Share components across teams and projects to speed up development and make sure your users experience a consistent design at every touchpoint.
Bit offers a great dev experience for building, sharing, and adopting components across teams and applications. Create a component hub for free give it a try →
Conclusion
Compared to React Router, React Location is a lot younger and some of the features are still under development. But, the React Location team has been able to reduce the gap between these 2 libraries by introducing 3rd party support libraries.
Also, it has a whole new set of features related to asynchronous routing and data loaders to put it ahead of React Router.
So, I invite you all to try our React Location for your next project and share your thought in the comments section.
Thank you for reading !!!
Learn More
- Common React Hooks Mistakes You Should Avoid
- Implementing Atomic Design with React and Bit
- React Error Handling and Logging Best Practices
Introduction to React Location was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Bits and Pieces - Medium and was authored by Chameera Dulanga
Chameera Dulanga | Sciencx (2021-11-22T21:39:24+00:00) Introduction to React Location. Retrieved from https://www.scien.cx/2021/11/22/introduction-to-react-location/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.