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.
branch from recompose is one of the best way to avoid if-else in your components branch( condition, leftHOC, rightHOC )(MyComponent) if the condition evaluates to true then. MyComponent is passed to the leftHOC else it is passed to the rightHOC.
Recompose allows us to write many smaller higher-order components and then we compose all those components together to get the desired component. It improves both readability and the maintainability of the code.
It's enough to have quick look at some useful things you should know about Jetpack compose recomposition. Recomposition is the process of calling composable again and again on input changes. In the legacy Android View system, we use invalidate() to do the same.
Recompose is a React utility belt for function components and higher-order components. Think of it like lodash for React.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With