Using Recompose’s Branch to Conditionally Render Components

Recompose’s branch is a useful tool when composing components. Two situations I find myself using it frequently are authentication and fetching.

First, let’s take a look at the definition for branch

branch(
test: (props: Object) => boolean,
left: HigherOrderComponent,
right: HigherOrderComponent
): HigherOrderComponent

It takes 3 arguments

  1. test a function that receives props as its only argument and must return a boolean
  2. left a higher order component that will be applied if test is true
  3. right a higher order component that will be applied if test is false

It will return `HigherOrderComponent` which means we will still need to call it as a function with our BaseComponent as the only argument.


Example

Here we use branch to conditionally apply wrapGreen or wrapRed to the Box component.

Remember, the left and right arguments are expected to be higher order functions so we have to provide a function not a React component.

Bonus Example

Conditionally rendering based on auth.

Home.js shows an example with code splitting

RedirectExample.js shows an example of using React Router’s Redirect component to redirect when unauthorized.