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

169
Visualizações
Extract Conditional Logic to Separate React Component

My React app has multiple functional components that repeats the same conditional logic, which I would like to extract to its own component to avoid duplicating it across all the components.

Below is an example of one of the pages that shows the repeated boilerplate code. If the global window.userPermission does not contain the value Page1, the user is redirected to the home page.

Is there some way to modularize this conditional logic including redirect, while passing it the permissions string (Page1, etc.)?

import ...

export default function SomeComponent() {

  // begin boilerplate code
  if (
    window.userPermission != null &&
    !window.userPermission.find(permission => permission.id == 'Page1')
  ) {
    return (
      <div>
        <Redirect to="/" />
      </div>
    );
  }
  // end boilerplate code

  return (
    <div>
      <Page1/>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Really easy just wrap your page in a wrapper component and if a value is true return the children or else redirect.

import {Redirect} from 'react-router-dom'

const SomeComponent = ({children, page}) => {
  if (
    window.userPermission != null &&
    !window.userPermission.find(permission => permission.id == page)
  ) return children

  return <Redirect to="/" />
}

export default SomeComponent

Then use this component like so:

<SomeComponent page="page1">
  <Page1/>
</SomeComponent>
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