tachyon-next-routing-utils
v32.0.0
Published
Utilities for advanced routing capabilities in Next.js apps
Downloads
2
Readme
Tachyon-Next-Routing-Utils
Routing utilities for Next applications using Next 9's file-system based routing.
Features:
- SSR compatible
- Optional path query stripping
- Route history
yarn add tachyon-next-routing-utils
Installation
import type { FC } from 'react';
import { SingletonRouter } from 'next/router';
import { RouterUtilsRoot } from 'tachyon-next-routing-utils';
const App: FC = ({ children }) => (
<RouterUtilsRoot preservedParams={['tt_medium']}>{children}</RouterUtilsRoot>
);
HOC
A withRouterUtils
HOC can be used to to consume route parameters (pathname,
asPath, query) and pageCount information in child components of a page:
import type { FC } from 'react';
import { withRouterUtils } from 'tachyon-next-routing-utils';
import type { RouterUtilsProps } from 'tachyon-next-routing-utils';
import { flattenHeaderOrParam } from 'tachyon-utils';
type QueryDependentComponentProps = RouterUtilsProps;
const QueryDependentComponentBase: FC<QueryDependentComponentProps> = ({
routerUtils,
}) => {
const { currentPathname, pageCount, currentQuery } = routerUtils;
const someQueryParam = flattenHeaderOrParam(currentQuery['<SOME_QUERY_KEY>']);
if (!someQueryParam) {
// ...
}
// ...
};
export const QueryDependentComponent = withRouterUtils(
QueryDependentComponentBase,
);
Custom Hook
A useRouterUtils
hook can be used to access the same information:
import { useRouterUtils } from 'tachyon-next-routing-utils';
export function CurrentRouteDependentComponent() {
const { currentPathname, pageCount, currentQuery } = useRouterUtils();
//...
}
Testing
You can use MockRouterUtilsProvider
to mock useRouterUtils
values:
import type { FC } from 'react';
import { MockRouterUtilsProvider } from 'tachyon-next-routing-utils';
const TestComponent: FC = () => (
<MockRouterUtilsProvider value={{ currentAsPath: '/' }}>
<ComponentUsingUseRouterUtils />
</MockRouterUtilsProvider>
);