Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

170
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!