function App() {
return (
<RecoilRoot>
<Router>
<Navbar />
<Routes>
<Route path={"/"} element={<Home />} />
<Route path={`/page/:menu`} element={<MovieMenu />} />
<Route path={`/movie/:id`} element={<Detail />} />
<Route path={`/search/:searchText`} element={<Search />} />
<Route path={"*"} element={<NotFound />} />
</Routes>
</Router>
</RecoilRoot>
);
}
If i process 404 page in the above way, /
handle it well, but <NotFound />
not be rendered if any path is entered after /page/fldlfsd;lf;
or /search/dsklfskldf
. Is there a way?
CodePudding user response:
Paths like "/page/fldlfsd;lf;"
and "/search/dsklfskldf"
will be matched and rendered by the Routes
component. The route param validation needs to occur in the routed component.
Each component can use the useParams
hook to access the route param, validate it, and redirect to the NotFound
route if param is invalid.
To help with this I suggest creating a discrete route to render NotFound
so you can imperatively redirect to it from components and create a redirect route to handle unknown routes.
Example:
function App() {
return (
<RecoilRoot>
<Router>
<Navbar />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/page/:menu" element={<MovieMenu />} />
<Route path="/movie/:id" element={<Detail />} />
<Route path="/search/:searchText" element={<Search />} />
<Route path="/404" element={<NotFound />} />
<Route path="*" element={<Navigate to="/404" replace />} />
</Routes>
</Router>
</RecoilRoot>
);
}
...
MovieMenu
const navigate = useNavigate();
const { menu } = useParams();
useEffect(() => {
... logic to validate menu param ...
if (invalidMenu) {
navigate("/404", { replace: true });
}
}, [menu, navigate]);
...
CodePudding user response:
Replace your /
route with an Index route.
Index routes can be thought of as "default child routes". When a parent route has multiple children, but the URL is just at the parent's path, you probably want to render something into the outlet.
function App() {
return (
<RecoilRoot>
<Router>
<Navbar />
<Routes>
<Route index element={<Home />} />
<Route path={`/page/:menu`} element={<MovieMenu />} />
<Route path={`/movie/:id`} element={<Detail />} />
<Route path={`/search/:searchText`} element={<Search />} />
<Route path={"*"} element={<NotFound />} />
</Routes>
</Router>
</RecoilRoot>
);
}