Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

allow Redirect to use navigate options.replace #4704

Merged
merged 5 commits into from
Mar 12, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
25 changes: 25 additions & 0 deletions packages/router/src/__tests__/router.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1191,6 +1191,31 @@ test('jump to new route, then go back', async () => {
await waitFor(() => screen.getByText('Home Page'))
})

test('redirect replacing route', async () => {
const ListWithDefaultParamsPage = (props) => {
if (props['_limit']) {
return <h1>List Page</h1>
}
return <Redirect to="/list?_limit=10" options={{ replace: true }} />
}
const TestRouter = () => (
<Router>
<Route path="/" page={HomePage} name="home" />
<Route path="/list" page={ListWithDefaultParamsPage} name="list" />
</Router>
)
const screen = render(<TestRouter />)

// starts on home page
await waitFor(() => screen.getByText('Home Page'))

act(() => navigate(routes.list()))
odjhey marked this conversation as resolved.
Show resolved Hide resolved
await waitFor(() => screen.getByText('List Page'))
act(() => back())
// without options.replace = true in Redirect, back would go to List Page
await waitFor(() => screen.getByText('Home Page'))
})

describe('trailing slashes', () => {
const TSNeverRouter = () => (
<Router trailingSlashes={'never'}>
Expand Down
7 changes: 4 additions & 3 deletions packages/router/src/links.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { forwardRef, useEffect } from 'react'

import { navigate } from './history'
import { navigate, NavigateOptions } from './history'
import { useLocation } from './location'
import { flattenSearchParams, matchPath } from './util'

Expand Down Expand Up @@ -151,13 +151,14 @@ const NavLink = forwardRef<
interface RedirectProps {
/** The path to redirect to */
to: string
options?: NavigateOptions
}

/**
* A declarative way to redirect to a route name
*/
const Redirect = ({ to }: RedirectProps) => {
useEffect(() => navigate(to), [to])
const Redirect = ({ to, options }: RedirectProps) => {
useEffect(() => navigate(to, options), [to, options])
return null
}

Expand Down