shlink-web-client/test/__helpers__/MemoryRouterWithParams.tsx

24 lines
811 B
TypeScript
Raw Permalink Normal View History

2023-12-19 01:38:34 +03:00
import type { FC, PropsWithChildren } from 'react';
import { useMemo } from 'react';
2024-12-09 13:52:58 +03:00
import { MemoryRouter, Route, Routes } from 'react-router';
2023-12-19 01:38:34 +03:00
export type MemoryRouterWithParamsProps = PropsWithChildren<{
params: Record<string, string>;
}>;
/**
* Wrap any component using useParams() with MemoryRouterWithParams, in order to determine wat the hook should return
*/
export const MemoryRouterWithParams: FC<MemoryRouterWithParamsProps> = ({ children, params }) => {
const pathname = useMemo(() => `/${Object.values(params).join('/')}`, [params]);
const pathPattern = useMemo(() => `/:${Object.keys(params).join('/:')}`, [params]);
return (
<MemoryRouter>
<Routes location={{ pathname }}>
<Route path={pathPattern} element={children} />
</Routes>
</MemoryRouter>
);
};