snippetjavascriptreactCritical
How can I redirect in React Router v6?
Viewed 0 times
redirectreactroutercanhow
Problem
I am trying to upgrade to React Router v6 (
Here is my updated code:
The last
However, I got an error
TS2322: Type '{ render: () => Element; }' is not assignable to type 'IntrinsicAttributes & (PathRouteProps | LayoutRouteProps | IndexRouteProps)'. Property 'render' does not exist on type 'IntrinsicAttributes & (PathRouteProps | LayoutRouteProps | IndexRouteProps)'.
However, based on the documentation, it does have
react-router-dom 6.0.1).Here is my updated code:
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';
} />
} />
} />
The last
Route is redirecting the rest of paths to /.However, I got an error
TS2322: Type '{ render: () => Element; }' is not assignable to type 'IntrinsicAttributes & (PathRouteProps | LayoutRouteProps | IndexRouteProps)'. Property 'render' does not exist on type 'IntrinsicAttributes & (PathRouteProps | LayoutRouteProps | IndexRouteProps)'.
However, based on the documentation, it does have
render for Route. How can I use it correctly?Solution
I think you should use the no match route approach.
Check this in the documentation: Adding a "No Match" Route
To keep the history clean, you should set
Check this in the documentation: Adding a "No Match" Route
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';
} />
} />
}
/>
To keep the history clean, you should set
replace prop. This will avoid extra redirects after the user click back.Code Snippets
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/lab" element={<Lab />} />
<Route
path="*"
element={<Navigate to="/" replace />}
/>
</Routes>
</BrowserRouter>Context
Stack Overflow Q#69868956, score: 397
Revisions (0)
No revisions yet.