replicate notFoundRoute functionality #1262
Unanswered
allan-vera
asked this question in
Q&A
Replies: 1 comment
-
The solution I found is to set notFoundMode to your router: main.tsx // Setup router instance
const router = createRouter({
routeTree,
notFoundMode: "root",
}); And with __root.tsx import { createRootRoute, Navigate, Outlet } from "@tanstack/react-router";
import { TanStackRouterDevtools } from "@tanstack/router-devtools";
export const Route = createRootRoute({
component: App,
notFoundComponent: NotFound, // Global Not Found Component
});
function App() {
return (
<>
<Outlet />
<TanStackRouterDevtools />
</>
);
}
function NotFound() {
return Navigate({ to: "/notFound" }); // Redirect to your notFound route
} It is also nice to add "replace" property to the Navigate so you can easily implement going back (if you won't add the "replace" property going back will redirect to the route that wasn't found and you'll end up on the same NotFound page so "replace" makes it actually go back to the last good path) const router = createRouter({
routeTree,
defaultNotFoundComponent: () => <Navigate to="/404" replace />,
}); function NotFoundPage() {
const router = useRouter();
const onBack = () => router.history.back();
return (
<div>
<h1>404 Not Found</h1>
<p>Sorry, the page you are looking for does not exist.</p>
<button onClick={onBack}>Go Back</button>
</div>
);
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I noticed recently that notFoundRoute is being deprecated in favor of notFoundComponent. However I am finding their behaviors very different within my app. One of the key differences that I noticed is that any unmatched route (with the existing routeTree), would match with /404. Which was really nice because it essentially allowed me to set a global not found page that works perfectly fine for my current use case. However, I notice that is no longer the case for notFoundComponent.
Is there a way to replicate this behavior? Furthermore, I am struggling to understand the difference between notFoundComponent and defaultNotFoundComponent and which one I should be using.
Beta Was this translation helpful? Give feedback.
All reactions