DEV Community

Discussion on: Conditionally render react components in cleaner way

Collapse
 
sultan99 profile image
Sultan • Edited

HOC is not an anti-pattern - it is HOF if we consider any component as a function, but hooks break the main FP rule - the function purity and I consider it as a side-effect. I agree with you, the best solution for this example are routers and HOC should be used for something else.

I prefer to create some helper functions which can be used across the project:

export const select = (...list) => value => list.reduce(
  (acc, next) => acc || next(value), null
)

export const when = (test, wanted) => value => (
  test === value && wanted
)
Enter fullscreen mode Exit fullscreen mode

and use them:

const DefaultSettings = () => (
  <p>What the Hell Are You?</p>
)

const selectSettings = select(
  when(`admin`, AdminSettings),
  when(`user`, UserSettings),
  when(`guest`, GuestSettings),
  () =>  DefaultSettings
)

const UserSettings = ({ userRole, username }) => {
  const Settings = selectSettings(userRole)
  return (
    <div>
      <h1>Settings</h1>
      <Settings username={username}/>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode