react-router-dom#Router TypeScript Examples
The following examples show how to use
react-router-dom#Router.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: test-utils.tsx From fhir-validator-app with Apache License 2.0 | 7 votes |
renderWithRouter = ( ui: JSX.Element, { route = '/', history = createMemoryHistory({ initialEntries: [route] }) }: RenderOptions = {} ): RenderResult & { history: MemoryHistory } => { const Wrapper: FC = ({ children }) => <Router history={history}>{children}</Router>; return { ...render(ui, { wrapper: Wrapper }), history, }; }
Example #2
Source File: CollectionList.test.tsx From firebase-tools-ui with Apache License 2.0 | 6 votes |
it('redirects to collection when clicking the collection list item and the ids have special characters', async () => {
const history = createMemoryHistory({ initialEntries: ['/firestore/data'] });
const { getByTestId } = await render(
<Router history={history}>
<Route path="/firestore/data">
<CollectionListItem
collectionId="sub-coll-1@#$"
routeMatchUrl="/coll-1%40%23%24/thing%40%23%24"
/>
</Route>
</Router>
);
fireEvent.click(getByTestId('firestore-collection-list-item'));
expect(history.location.pathname).toBe(
'/coll-1%40%23%24/thing%40%23%24/sub-coll-1%40%23%24'
);
});
Example #3
Source File: Router.tsx From icejs with MIT License | 6 votes |
export function IceRouter(props: RouterProps) {
const { type, routes, fallback, ...others } = props;
// parse routes before render
const parsedRoutes = parseRoutes(routes);
const children = <Routes routes={parsedRoutes} fallback={fallback} />;
return type === 'static' ?
<StaticRouter {...others}>
{children}
</StaticRouter> :
<Router {...others}>
{children}
</Router>;
}
Example #4
Source File: Flow.test.tsx From glific-frontend with GNU Affero General Public License v3.0 | 6 votes |
it('should edit the flow', async () => {
const history: any = createBrowserHistory();
history.push({ pathname: `/flow/1/edit` });
const editFlow = (match: any) => (
<MockedProvider mocks={mocks} addTypename={false}>
<Router history={history}>
<Flow match={match} />
</Router>
</MockedProvider>
);
const { container, getByTestId } = render(editFlow({ params: { id: 1 } }));
await waitFor(() => {});
});
Example #5
Source File: index.test.tsx From firebase-tools-ui with Apache License 2.0 | 6 votes |
describe('Storage Route', () => {
it('displays the children', async () => {
const history = createMemoryHistory({ initialEntries: ['/storage'] });
const wrapperId = 'wrapper-id';
const { findByTestId } = render(
<FakeStorageWrappers fallbackTestId={'lol'}>
<Router history={history}>
<StorageRoute>
<div data-testid={wrapperId} />
</StorageRoute>
</Router>
</FakeStorageWrappers>
);
await findByTestId(wrapperId);
expect(history.location.pathname).toMatch(/storage\/bucket.*/);
});
});
Example #6
Source File: ConfigurationMain.tsx From console with GNU Affero General Public License v3.0 | 6 votes |
ConfigurationMain = () => {
return (
<Router history={history}>
<Switch>
<Route path="/settings" component={ConfigurationOptions} />
<Route component={NotFoundPage} />
</Switch>
</Router>
);
}
Example #7
Source File: useBuckets.test.tsx From firebase-tools-ui with Apache License 2.0 | 6 votes |
describe('useBuckets', () => {
async function setup() {
const history = createMemoryHistory({
initialEntries: ['/storage/' + initialBucketName],
});
mockBuckets(buckets);
const Wrapper: React.FC<React.PropsWithChildren<unknown>> = ({
children,
}) => {
return (
<Router history={history}>
<Route exact path={storagePath + `:bucket/:path*`}>
<TestStorageProvider>
<Suspense fallback={'lol'}>{children}</Suspense>
</TestStorageProvider>
</Route>
</Router>
);
};
const { result } = renderHook(() => useBuckets(), {
wrapper: Wrapper,
});
await waitFor(() => delay(100));
return { buckets: result.current };
}
it('combines buckets from server and from URL', async () => {
const { buckets } = await setup();
expect(buckets).toEqual(['blinchik', 'pelmeni', initialBucketName]);
});
});
Example #8
Source File: Policies.tsx From console with GNU Affero General Public License v3.0 | 6 votes |
Policies = () => {
return (
<Router history={history}>
<Switch>
<Route
path={IAM_PAGES.POLICIES}
exact={true}
component={ListPolicies}
/>
<Route
path={`${IAM_PAGES.POLICIES}/:policyName+`}
component={PolicyDetails}
/>
<Route path="/" component={ListPolicies} />
<Route component={NotFoundPage} />
</Switch>
</Router>
);
}
Example #9
Source File: TableRow.test.tsx From firebase-tools-ui with Apache License 2.0 | 6 votes |
describe('RequestsTableRow', () => {
it('redirects to corresponding request details path when clicking table row', async () => {
const history = createMemoryHistory({
initialEntries: ['/firestore/requests'],
});
const { getByRole } = render(
<Router history={history}>
<table>
<RequestsTableRow
request={FAKE_EVALUATION}
requestId={FAKE_EVALUATION_ID}
setShowCopyNotification={SET_SHOW_COPY_NOTIFICATION}
/>
</table>
</Router>
);
await act(async () => {
fireEvent.click(getByRole('row'));
});
expect(history.location.pathname).toBe(
`/firestore/requests/${FAKE_EVALUATION_ID}`
);
});
});
Example #10
Source File: Users.tsx From console with GNU Affero General Public License v3.0 | 6 votes |
Users = () => {
return (
<Router history={history}>
<Switch>
<Route path={IAM_PAGES.USER_ADD} exact component={AddUserScreen} />
<Route path={IAM_PAGES.USERS_VIEW} exact component={UserDetails} />
<Route path={IAM_PAGES.USERS} exact component={ListUsers} />
<Route component={NotFoundPage} />
</Switch>
</Router>
);
}
Example #11
Source File: AppRoutes.tsx From whiteboard-demo with MIT License | 6 votes |
public render(): React.ReactNode {
return (
<Router history={history}>
<Switch>
<Route path="/replay/:identity/:uuid/:userId/:region" component={ReplayPage} />
<Route path="/replay-video/:identity/:uuid/:userId/:region" component={ReplayVideoPage} />
<Route path="/whiteboard/:identity/:uuid/:userId/:region" component={WhiteboardPage} />
<Route path="/whiteboard/:identity/:uuid/:region" component={WhiteboardCreatorPage} />
<Route path="/history/" component={HistoryPage} />
<Route path="/join/" component={JoinPage}/>
<Route path="/create/" component={CreatePage}/>
<Route path="/name/:uuid?/" component={AddNamePage}/>
<Route path="/storage/" component={Storage}/>
<Route path="/" component={IndexPage}/>
</Switch>
</Router>
);
}
Example #12
Source File: LoginProvider.test.tsx From antibody-web with MIT License | 6 votes |
describe("<LoginProvider>", () => {
it("Renders the contents correctly when the user has the login cookie set", () => {
const cookieStub = { get: () => "yes" };
const provider = render(
<LoginProvider cookies={cookieStub}>
<span data-testid="children-elements">Meow</span>
</LoginProvider>
);
expect(provider.getAllByTestId("children-elements")).toHaveLength(1);
});
it("Redirects to / if the user is not logged in", () => {
const cookieStub = { get: () => undefined };
const historySpy = createMemoryHistory({
initialEntries: ["/some-route-with-login"],
});
render(
<Router history={historySpy}>
<LoginProvider cookies={cookieStub}>
<div />
</LoginProvider>
</Router>
);
expect(historySpy.location.pathname).toEqual("/");
});
});
Example #13
Source File: CollectionList.test.tsx From firebase-tools-ui with Apache License 2.0 | 6 votes |
it('redirects to collection when clicking the collection list item', async () => {
const history = createMemoryHistory({ initialEntries: ['/firestore/data'] });
const { getByTestId } = await render(
<Router history={history}>
<Route path="/firestore/data">
<CollectionListItem
collectionId="sub-coll-1"
routeMatchUrl="/coll-1/thing"
/>
</Route>
</Router>
);
fireEvent.click(getByTestId('firestore-collection-list-item'));
expect(history.location.pathname).toBe('/coll-1/thing/sub-coll-1');
});
Example #14
Source File: testUtils.tsx From rhub-app with MIT License | 6 votes |
connectedRender = (
ui: ReactElement,
state = {},
route = '/',
{ ...renderOptions } = {}
) => {
const store = mockStore(state);
const history = createMemoryHistory({ initialEntries: [route] });
const Wrapper = ({ children }: { children?: ReactNode }) => {
return (
<Provider store={store}>
<Router history={history}>{children}</Router>
</Provider>
);
};
return {
store,
history,
result: rtlRender(ui, { wrapper: Wrapper, ...renderOptions }),
};
}
Example #15
Source File: App.tsx From vvs-ui with GNU General Public License v3.0 | 6 votes |
function App() {
return (
<Router history={history}>
<ScrollToTop>
<ResetCSS />
<GlobalStyle />
<Menu>
<SuspenseWithChunkError fallback={<PageLoader />}>
<Switch>
<Route path="/" exact>
<Home />
</Route>
</Switch>
</SuspenseWithChunkError>
</Menu>
</ScrollToTop>
</Router>
);
}
Example #16
Source File: routesTest.tsx From devex with GNU General Public License v3.0 | 6 votes |
describe('react router test', () => {
const history = createMemoryHistory()
it('renders layout', () => {
const homePage = shallow(
<Router history={history}>
<Layout />
</Router>
)
expect(homePage.find(Layout)).toHaveLength(1)
})
it('renders a spinner when in network transition', () => {
const homePage = mount(
<Router history={history}>
<NetworkContext.Provider value={{
isValidUrl: null,
isIsolatedServer: true,
dataService: null,
networkUrl: '',
inTransition: true,
isLoadingNetworks: true
}}>
<App />
</NetworkContext.Provider>
</Router>
)
expect(homePage.find(Spinner)).toHaveLength(1)
})
})
Example #17
Source File: Invitation.test.tsx From convoychat with GNU General Public License v3.0 | 6 votes |
describe("Invitation", () => {
it("Invitation", async () => {
// MOCK ROUTER https://testing-library.com/docs/example-react-router
const history = createMemoryHistory();
const { getByText, queryByTestId } = renderWithStyledTheme(
<MockedProvider mocks={mocks} addTypename={false}>
<Router history={history}>
<AuthProvider>
<NotificationsWithPortal />
<Invitation />
</AuthProvider>
</Router>
</MockedProvider>
);
history.push("/invitation/" + FAKE_TOKEN);
expect(queryByTestId("loading")).toBeInTheDocument();
await wait(0);
expect(queryByTestId("loading")).not.toBeInTheDocument();
expect(getByText("AmazingRoom")).toBeInTheDocument();
expect(getByText(/Anurag Hazra/i)).toBeInTheDocument();
expect(getByText(/Accept Invitation/i)).toBeInTheDocument();
expect(history.location.pathname).toBe("/invitation/" + FAKE_TOKEN);
// ACCEPT
let button = getByText(/Accept Invitation/i);
await act(async () => fireEvent.click(button));
await wait(0);
// CHECK redirection
expect(history.location.pathname).toBe("/");
});
});
Example #18
Source File: index.tsx From MagicUI with Apache License 2.0 | 6 votes |
function App() {
const router = (
<Router history={history}>
<Switch>
<Route path="/" exact>
<Login/>
</Route>
<Route path="/register">
<Register/>
</Route>
</Switch>
</Router>
);
return (
<div className={style.app}>
<div className={style.header}>
<ControlButtonGroup close onClose={close} minimize onMinimize={minimize}/>
</div>
<div className={style.content}>
{router}
</div>
</div>
);
}
Example #19
Source File: render-helper.tsx From clean-react with GNU General Public License v3.0 | 6 votes |
renderWithHistory = ({ Page, history, account = mockAccountModel(), states = [] }: Params): Result => {
const setCurrentAccountMock = jest.fn()
const mockedState = {
setCurrentAccount: setCurrentAccountMock,
getCurrentAccount: () => account
}
const initializeState = ({ set }: MutableSnapshot): void => {
[...states, { atom: currentAccountState, value: mockedState }].forEach(state => set(state.atom, state.value))
}
render(
<RecoilRoot initializeState={initializeState}>
<Router history={history}>
<Page />
</Router>
</RecoilRoot>
)
return {
setCurrentAccountMock
}
}
Example #20
Source File: AppRouter.tsx From querybook with Apache License 2.0 | 6 votes |
AppRouter: React.FunctionComponent = () => (
<Router history={history}>
<UserLoader>
<AppLayout>
<React.Suspense fallback={<Loading fullHeight />}>
<Switch>
<Route path="/admin/:entity?" component={AppAdmin} />
<Route
exact
path="/"
render={() => <EnvironmentsRouter />}
/>
<Route path="/:env/" component={EnvironmentsRouter} />
<Route component={FourOhFour} />
</Switch>
</React.Suspense>
</AppLayout>
</UserLoader>
<ConfirmationManager />
<ToastManager />
</Router>
)
Example #21
Source File: testUtils.tsx From rhub-app with MIT License | 6 votes |
connectedRender = (
ui: ReactElement,
state = {},
route = '/',
path = '/',
{ ...renderOptions } = {}
) => {
const store = mockStore(state);
const history = createMemoryHistory({ initialEntries: [route] });
const Wrapper = ({ children }: { children?: ReactNode }) => {
return (
<Provider store={store}>
<Router history={history}>
<Route path={path}>{children}</Route>
</Router>
</Provider>
);
};
return {
store,
history,
result: rtlRender(ui, { wrapper: Wrapper, ...renderOptions }),
};
}
Example #22
Source File: main.test.tsx From filecoin-CID-checker with Apache License 2.0 | 6 votes |
describe('<Main /> spec', () => {
it('renders the component', async () => {
const history = createMemoryHistory()
const { container, getByTestId } = render(
<ThemeProvider theme={theme}>
<Router history={history}>
<Main />
</Router>
</ThemeProvider>,
)
expect(container.innerHTML).toMatch(/Search by Piece CID, Deal ID, or Miner ID/i)
const loading = getByTestId('loading')
expect(loading).toBeInTheDocument()
})
})
Example #23
Source File: App.tsx From erda-ui with GNU Affero General Public License v3.0 | 6 votes |
function App() {
return (
<Router history={history}>
<Switch>
<Route exact path="/:orgName/market/download/:publishItemId" component={DownloadPage} />
<Route path="*" component={NotFound} />
</Switch>
</Router>
);
}
Example #24
Source File: images.test.tsx From filecoin-CID-checker with Apache License 2.0 | 6 votes |
describe('<Logo /> spec', () => {
it('renders the component', async () => {
const history = createMemoryHistory()
const { container } = render(
<Router history={history}>
<Logo />{' '}
</Router>,
)
expect(container).toMatchSnapshot()
})
})
Example #25
Source File: App.tsx From surveyo with Apache License 2.0 | 5 votes |
function App() {
const {isAuthenticated, isLoading, getIdTokenClaims} = useAuth0();
return (
<ApolloProvider
client={createApolloClient(isAuthenticated ? getIdTokenClaims : null)}
>
<Router history={history}>
<div className="box">
<div className="row header">
<SyMenu />
</div>
<div className="row content">
<main>
{isLoading ? (
<Loading />
) : (
<Switch>
<Route
exact
path="/"
component={isAuthenticated ? Dashboard : Home}
/>
<Route exact path="/form/:id" component={FormPage} />
<PrivateRoute exact path="/create" component={FormCreator} />
<PrivateRoute exact path="/charts/:id" component={VizPage} />
<PrivateRoute
exact
path="/graphiql/:id"
component={Graphiql}
/>
</Switch>
)}
</main>
</div>
</div>
</Router>
</ApolloProvider>
);
}
Example #26
Source File: Buckets.tsx From console with GNU Affero General Public License v3.0 | 5 votes |
Buckets = () => {
return (
<Router history={history}>
<Switch>
<Route
path={IAM_PAGES.ADD_BUCKETS}
children={(routerProps) => (
<Suspense fallback={<LoadingComponent />}>
<AddBucket />
</Suspense>
)}
/>
<Route
path="/buckets/:bucketName/admin/*"
children={(routerProps) => (
<Suspense fallback={<LoadingComponent />}>
<BucketDetails {...routerProps} />
</Suspense>
)}
/>
<Route
path="/buckets/:bucketName/admin"
children={(routerProps) => (
<Suspense fallback={<LoadingComponent />}>
<BucketDetails {...routerProps} />
</Suspense>
)}
/>
<Route
path="/buckets/:bucketName/browse/:subpaths+"
children={(routerProps) => (
<Suspense fallback={<LoadingComponent />}>
<BrowserHandler {...routerProps} />
</Suspense>
)}
/>
<Route
path="/buckets/:bucketName/browse"
children={(routerProps) => (
<Suspense fallback={<LoadingComponent />}>
<BrowserHandler {...routerProps} />
</Suspense>
)}
/>
<Route
path="/buckets/:bucketName"
component={() => <Redirect to={`/buckets`} />}
/>
<Route
path="/"
children={(routerProps) => (
<Suspense fallback={<LoadingComponent />}>
<ListBuckets {...routerProps} />
</Suspense>
)}
/>
<Route
children={(routerProps) => (
<Suspense fallback={<LoadingComponent />}>
<NotFoundPage />
</Suspense>
)}
/>
</Switch>
</Router>
);
}
Example #27
Source File: index.tsx From MagicUI with Apache License 2.0 | 5 votes |
App: React.FC<IAppProps> = (props: IAppProps) => {
const dispatch = useDispatch();
useOnMount(() => {
onCreateWindow((data: any) => {
fetchSystemSettings(data.email).then(res => {
if (!res.err) {
dispatch(saveSettings(res.settings));
}
});
dispatch(saveUser(data));
});
onUpdateUser((data: any) => {
console.log('user data', data);
dispatch(saveUser(data));
});
});
const router = (
<Router history={history}>
<Switch>
<Route path={Routers.MAIN} exact>
<Main/>
</Route>
<Route path={Routers.WEBGL_EDITOR}>
<WebGLEditor/>
</Route>
<Route path={Routers.DSL_CODE_EDITOR}>
<DslCodeEditor/>
</Route>
<Route path={Routers.HELP}>
<Help/>
</Route>
<Route path={Routers.SETTINGS}>
<Settings/>
</Route>
</Switch>
</Router>
);
return (
<div className={style.app}>
<ToolBar/>
<div className={style.navigation_wrapper}>
<Navigation/>
</div>
<div className={style.page_wrapper}>
{router}
</div>
</div>
);
}
Example #28
Source File: App.tsx From foodie with MIT License | 5 votes |
function App() {
const [isCheckingSession, setCheckingSession] = useState(true);
const dispatch = useDispatch();
const isNotMobile = window.screen.width >= 800;
useEffect(() => {
(async () => {
try {
const { auth } = await checkAuthSession();
dispatch(loginSuccess(auth));
socket.on('connect', () => {
socket.emit('userConnect', auth.id);
console.log('Client connected to socket.');
});
// Try to reconnect again
socket.on('error', function () {
socket.emit('userConnect', auth.id);
});
setCheckingSession(false);
} catch (e) {
console.log('ERROR', e);
setCheckingSession(false);
}
})();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return isCheckingSession ? (
<Preloader />
) : (
<Router history={history}>
<main className="relative min-h-screen">
<ToastContainer
position="bottom-left"
autoClose={5000}
transition={Slide}
draggable={false}
hideProgressBar={true}
bodyStyle={{ paddingLeft: '15px' }}
/>
<NavBar />
<Switch>
<PublicRoute path={ROUTE.REGISTER} component={pages.Register} />
<PublicRoute path={ROUTE.LOGIN} component={pages.Login} />
<ProtectedRoute path={ROUTE.SEARCH} component={pages.Search} />
<Route path={ROUTE.HOME} exact render={(props: any) => <pages.Home key={Date.now()} {...props} />} />
<ProtectedRoute path={ROUTE.POST} component={pages.Post} />
<ProtectedRoute path={ROUTE.PROFILE} component={pages.Profile} />
<ProtectedRoute path={ROUTE.CHAT} component={pages.Chat} />
<ProtectedRoute path={ROUTE.SUGGESTED_PEOPLE} component={pages.SuggestedPeople} />
<Route path={ROUTE.SOCIAL_AUTH_FAILED} component={pages.SocialAuthFailed} />
<Route component={pages.PageNotFound} />
</Switch>
{isNotMobile && <Chats />}
</main>
</Router>
);
}
Example #29
Source File: index.tsx From End-to-End-Web-Testing-with-Cypress with MIT License | 5 votes |
ReactDOM.render(
<Router history={history}>
<ThemeProvider theme={theme}>
<App />
</ThemeProvider>
</Router>,
document.getElementById("root")
);