Skip to content

Commit

Permalink
allow Redirect to use navigate options.replace (#4704)
Browse files Browse the repository at this point in the history
Co-authored-by: Tobbe Lundberg <tobbe@tlundberg.com>
  • Loading branch information
odjhey and Tobbe committed Mar 12, 2022
1 parent 80cd0ae commit 71380ba
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
27 changes: 27 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,33 @@ 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'))

// This will navigate to /list, which will then redirect to /list?_limit=10
// which will render `<h1>List Page</h1>`
act(() => navigate(routes.list()))
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

0 comments on commit 71380ba

Please sign in to comment.