Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

168
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda