I am trying to make my website redirect to a 404 page when the path is not set, using vite-react-ssg and react-router-dom. I need to use SSG because of pre-rendering. I can't find any documentation on how to do this. vite-react-ssg
Has anyone tried it? Is it possible to do so?
I try something like this, but it didn't work:
export const routes = [
{
path: '/',
Component: Layout,
children: [
{
path: '404',
Component: lazy(() => import('@components/NotFound')),
},
{
path: '*',
redirect: '404',
},
...
]
},
]
I need examples or documentation on how to redirect an unconfigured route in react using vite-react-ssg pre-rendering.
I was trying that if for example it enters the path
"/no-configured"
it redirects it to the path"/404"
, but it didn't work.
What you have shown only works if user navigates to "/404" on the client directly. If you are wanting to define a "catch-all" route that redirects to this 404 path/page then import and use the Navigate
component from react-router-dom
and render a redirect.
import { Navigate } from 'react-router-dom';
...
export const routes = [
{
path: '/',
Component: Layout,
children: [
{
path: '404',
Component: lazy(() => import('@components/NotFound')),
},
{
path: '*',
element: <Navigate to="/404" replace />,
},
...
]
},
]
FWIW redirect
isn't a recognized Route
component prop. See Type Declaration (or view source code for what vite-react-ssg
imports from react-router-dom
).
interface RouteObject { path?: string; index?: boolean; children?: RouteObject[]; caseSensitive?: boolean; id?: string; loader?: LoaderFunction; action?: ActionFunction; element?: React.ReactNode | null; hydrateFallbackElement?: React.ReactNode | null; errorElement?: React.ReactNode | null; Component?: React.ComponentType | null; HydrateFallback?: React.ComponentType | null; ErrorBoundary?: React.ComponentType | null; handle?: RouteObject["handle"]; shouldRevalidate?: ShouldRevalidateFunction; lazy?: LazyRouteFunction<RouteObject>; }