I need the router redirects to the page "/"
when the URL doesn't have any queryString parameters ("/domain/search"
). But if it has any, for example "/domain/search?keyword=something&page=1"
, it should go on and render the component Movies
.
My code below doesn't work, it still redirects to "/"
even if the URL has some queryString parameters.
Please help with this problem.
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<Search />} />
<Route path="search" element={<Navigate to="/" />} />
<Route path="search/*" element={<Movies />} />
</Route>
</Routes>
You have to use useSearchParams
in the Movies
component to read the query string in the URL:
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<Search />} />
<Route path="search" element={<Movies />} />
</Route>
</Routes>
Movies
component:import { Navigate, useSearchParams } from "react-router-dom";
function Movies(props) {
const [searchParams, setSearchParams] = useSearchParams();
const page = searchParams.get("page");
const otherParam = searchParams.get("otherParam");
if(!page && !otherParam) {
return <Navigate to="/" replace />
}
// the rest of your component
...
}
Or using URLSearchParams.keys()
import { Navigate, useSearchParams } from "react-router-dom";
function Movies() {
const [searchParams, setSearchParams] = useSearchParams();
if (![...searchParams.keys()].length) {
return <Navigate to="/" replace />;
}
return <span>Movies page</span>;
}
react-router-dom
and the Route
component doesn't use or reference the URL queryString when matching routes. This is something the routed component should check or something you can create a special layout route component to handle. The code should use the useSearchParams
hook to access the searchParams
and check for the existence of any params.
Example:
This example is a layout route that checks the search params entries array length and if there are entries an Outlet
component is rendered for any nested Route
components to render their element
prop out on, otherwise a redirect back to "/"
is rendered.
import { Navigate, Outlet, useSearchParams } from 'react-router-dom';
const ParamsRoute = () => {
const [searchParams] = useSearchParams();
return searchParams.entries().length
? <Outlet />
: <Navigate to="/" replace />
};
Usage:
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<Search />} />
<Route element={<ParamsRoute />}>
<Route path="search" element={<Movies />} />
</Route>
</Route>
</Routes>
Perhaps you want specific queryString parameters to be present:
import { Navigate, Outlet, useSearchParams } from 'react-router-dom';
const ParamsRoute = ({ params = [] }) => {
const [searchParams] = useSearchParams();
return searchParams.entries().length // has params
&& params.every(param => searchParams.get(param)) // has required params
? <Outlet />
: <Navigate to="/" replace />
};