useRedirect hook
See original GitHub issueIt would be nice to be able to setup redirects via a useRedirect
hook or similar mechanism.
I expect the router to navigate the user to the target path (preserving the queryString if present) and replacing the navigation history with the destination path.
Basic example
import {useRoutes, useRedirect} from 'raviger';
const routes = {
'/dashboard': () => 'Dashboard'
};
const MyApp = () => {
useRedirect('/', '/dashboard);
return useRoutes(routes) || 'oops';
}
I’d expect the user to end up in the /dashboard page when hitting the root of the App and having only /dashboard in its History.
Extra
Could be interesting to think about merging queryParameters defined in the useRedirect
hook configuration with the ones provided in a Link.
For example I could setup a redirect such as
useRedirect('/', '/dashboard?redirected=1');
Or
useRedirect('/', '/dashboard', {redirected: 1});
And then later in a hypothetical SomePage component make a Link to go back to the Dashboard
<Link href='/?from='some-page''>Go back</Link>
In this case I’d expect the queryParameters to contain both redirected
and from
But this is already quite advanced, I’d be very happy already with the Basic functionality 😃
Issue Analytics
- State:
- Created 4 years ago
- Reactions:1
- Comments:12 (6 by maintainers)
Top GitHub Comments
Indeed. For login it would work fine. For other pages not so much; it would leave the url out of sync or create multiple routes for the same component.
Eg: Overview would render both under
/
and/overview
. useRedirect fixes the problem entirely 😃If thats the case, you can skip the redirect and just return the
<Login>
component when they aren’t logged in. If the whole app is authenticated you can put this at the top level, above the router.