Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

257
Visualizações
React Router v6 redirect when there are not any url queryString parameters

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>
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You have to use useSearchParams in the Movies component to read the query string in the URL:

  1. The Routes:
<Routes>
  <Route path="/" element={<Layout />}>
    <Route index element={<Search />} />
    <Route path="search" element={<Movies />} />
  </Route>
</Routes>
  1. the 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
  ...

}

Edit restless-wildflower-959qx6

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>;
}

Edit red-meadow-urtrbn

about 4 years ago · Juan Pablo Isaza Relatório

0

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 />
};
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda