vamsiampolu
vamsiampolu

Reputation: 6622

Using branch from recompose

I am refactoring a stateless functional component to use branch and renderComponent from recompose.

The original component looks like this:

const Icon = props => {
  const { type, name } = props
  let res
  if (type === 'font') {
    return (<FontIcon name={name} />)
  } else if (type === 'svg') {
    res = (<SvgIcon glyph={name} />)
  }

  return res
}

The component with branch looks like this:

const isFont = props => {
  const { type } = props
  return type === 'font'
}

const FontIconHoC = renderComponent(FontIcon)
const SvgIconHoC = renderComponent(SvgIcon)

const Icon = branch(isFont, FontIconHoC, SvgIconHoC)

Icon.propTypes = {
  type: string,
  name: string
}

export default Icon

I try and render the component using:

<Icon name='crosshairs' type='font' />

The resulting error looks like this:

invariant.js:44Uncaught Error: Icon(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

Upvotes: 5

Views: 3698

Answers (2)

Bradford Medeiros
Bradford Medeiros

Reputation: 1791

You can also just use an if statement instead of branch. Consider that you just had some difficulties doing what an if statement does.

Maybe time to reconsider that library ?

Upvotes: -4

wuct
wuct

Reputation: 10477

branch returns a HOC, which accepts a component and return a component, so branch(...) is a HOC and branch(...)(...) is a component.

In your case, because Icon is not a component but a HOC, so React can't render it. To fix it, you can move SvgIcon out from branch's arguments and apply it to the HOC returned by branch(...), ex:

const Icon = branch(
  isFont,
  FontIconHoC,
  a => a
)(SvgIcon)

We apply an identity function (a => a) to the third argument of branch. You can think of the identity function is also a HOC, which basically just return the component it gets and does nothing more.

Because this pattern is used very often, so the third argument of branch is default to the identity function. As a result, we can omit it and make our code simpler:

const Icon = branch(
  isFont,
  FontIconHoC
)(SvgIcon)

I've created a jsfiddle for these code. You can try it here.

Upvotes: 13

Related Questions