TanStackT
TanStack2y ago
15 replies
incredible-moccasin

How do I render a Default (root level) Not Found Component within a layout.

Hi,

I would like to render all notFound components within a layout. Is there a simple way to achieve this?

I am using file routing, vite, react and typescript.
I have tried adding a notFound component to a pathless _layout.

export const Route = createFileRoute('/_layout')({
  component: LayoutComponent,
  notFoundComponent: () => <div> Not found at root but inside a layout </div>
})


When navigating to '<host>/wrongpath', only the default NotFoundComponent is rendered without the layout.

Other options I have considered:
1. Moving my layout to __root.tsx. The problem with this is that I have some routes I would like to render without the layout. Adding the _ suffix to them doesn't seem to bypass the root route as a parent.
2. Including the layout in the path and passing from props to make Link's relative. This ensures that invalid links that I generate are caught and improves some UX, but doesn't catch <host>/wrongpath URL's.
3. Wrapping my NotFoundComponent in the Layout component. Is this even allowed? Does <Outlet> work like a child if used outside of the router?
4. Catching a NotFoundError and re-directing to a NotFound route within the _layout. I don't really want to introduce too much boilerplate with this and it would mean changing the URL that the user see's.

Am I missing something for this task that I would have thought is fairly trivial? Any help would be appreciated.
Thanks in advance and thanks to the developers of this library.

Regards,
Simon
Was this page helpful?