Home > OS >  React navigate conditionally with useSearchParams
React navigate conditionally with useSearchParams

Time:08-22

How can I check whether there is any query string with route v6? I would like to achieve the same result as below ternary condition with searchParams

const redirect = location.search ? location.search.split("=")[1] : "/";
  useEffect(() => {
    if (userInfo) {
      navigate(redirect);
    }
  }, [navigate, userInfo, redirect]);

For instance, if there is any query string like the below it should redirect to shipping if not it should redirect to /

  const checkoutHandler = () => {
    navigate('/login?redirect=shipping')
  }

I tried something below but it did not work for me.

const [searchParams] = useSearchParams(); 
const redirect = searchParams ? searchParams.get('redirect') : "/";

App.js

<BrowserRouter>
  <Header />
  <Container>
    <Routes>
      <Route path="/shipping" element={<ShippingScreen />} />
      <Route path="/login" element={<LoginScreen />} />
      <Route path="/register" element={<RegisterScreen />} />
      <Route path="/" element={<HomeScreen />} />
    </Routes>
  </Container>
  <Container>
    <Footer />
  </Container>
</BrowserRouter>

CodePudding user response:

The implementation you have appears is mostly correct.

const redirect = searchParams ? searchParams.get('redirect') : "/";

The searchParams will always be a defined URLSearchParams object, so the redirect variable is assigned the result value of searchParams.get('redirect') which will either be the actual "redirect" query parameter value, i.e. "shipping" or null if it doesn't exist. Something like const redirect = searchParams.get('redirect') ? searchParams.get('redirect') : "/"; would be a bit more correct.

An additional issue I see is one of relative vs absolute path navigation. With a URL path/queryString like "/login?redirect=shipping" the redirect value is "shipping" and the navigate function will try to navigate relative to the current matched path.

You could prepend a leading "/" character to the path to make it an absolute path.

Example:

const navigate = useNavigate();
const [searchParams] = useSearchParams();

...

const redirect = searchParams.get('redirect');

...

navigate(`/${redirect ?? ""}`, { replace: true });

It would of course be better to pass the target path formatted as you expect to begin with, i.e. make the URL path/search something more like "/login?redirect=/shipping".

const navigate = useNavigate();
const [searchParams] = useSearchParams();

...

const redirect = searchParams.get('redirect');

...

navigate(redirect ?? "/", { replace: true });
  • Related