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

246
Visualizações
React Router: Having one Route conditionally render component based on url search param

Here's a scenario example:

I have two components and

The search params look like this: ?A=123&B=456

The Route is like this path="/home"

I want A to load on the route if only A is present in the search params (e.g. ?A=123), I want B to load if there is B in the search params (B also loads if both A and B are in the search params).

Can I do something inside the Route component where I can have a conditional render based on that and how would I go about doing that?

AKA:

<Route
path="/home"
if(urlparam.B){
render={<B/>}
} else {
render={<A/>}
}
</Route>

how can I pass the url to the route so it can check?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can't do this in the Route component, but you can create a wrapper component to handle this.

You can access the current location object's search string. From here you can create a URLSearchParams object and access the queryString parameters and apply the conditional rendering logic.

  • location

    Locations represent where the app is now, where you want it to go, or even where it was. It looks like this:

     {
       key: 'ac3df4', // not with HashHistory!
       pathname: '/somewhere',
       search: '?some=search-string',
       hash: '#howdy',
       state: {
         [userDefined]: true
       }
     }
    
  • URLSearchParams

Code

const Wrapper = ({ location }) => {
  const { search } = location;
  const searchParams = new URLSearchParams(search);

  const hasAParam = searchParams.get("A");
  const hasBParam = searchParams.get("B");

  if (hasAParam && !hasBParam) { // only A and not B
    return <A />;
  } else if (hasBParam) {        // only B
    return <B />;
  }
  return null; // render nothing
};

...

<Route path="/home" component={Wrapper} />

This assumes you are using react-router-dom@5.

If using v6, then use the useSearchParams hook directly.

useSearchParams

Example:

const Wrapper = () => {
  const [searchParams] = useSearchParams();

  const hasAParam = searchParams.get("A");
  const hasBParam = searchParams.get("B");

  if (hasAParam && !hasBParam) { // only A and not B
    return <A />;
  } else if (hasBParam) {        // only B
    return <B />;
  }
  return null; // render nothing
};

...

<Route path="/home" element={<Wrapper />} />
about 4 years ago · Juan Pablo Isaza Relatório

0

try this:

<Route
path="/home"
render={urlparam?.B ? <B/> : <A/>}
></Route>

In this case you can use the ternary operator to solve your problem

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