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