Reputation: 1334
I've searched around and after reading some stuff, I still didn't get when I use recompose
branch
over if-else
statement in react or why even use it?
can anyone mention a good source or explain it?
thanks
Upvotes: 7
Views: 3867
Reputation: 557
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
Suppose you have to show a loading state till the time data is not available then we can also use renderComponent from recompose
branch(
props=>props.loading,
renderComponent(Loader),
myComponent=>myComponent,
)(MyComponent)
Upvotes: 2
Reputation: 3441
While Estus answer is good enough and answered how used instead of if..else or ternary operator, I like to mention one another of use cases of branch that we using in our project, when we want to render a component within another component based on some conditions with help of renderComponent() which is useful in combination with branch() ( In our project Usually we use it to render dumb components, modals components , etc )
branch<WrappedProps>(
props => props.success,
renderComponent(ShowSuccessModal)
)
So in this example whenever props.success
in our container became true, the modal component will rendered.
Upvotes: 0
Reputation: 222513
It can be used instead of if..else
or ternary operator where function composition is preferred. Recompose provides function composition for React components. As other Recompose higher-order components, branch
HOC can be composed with compose
:
const fooPredicate = ({ type }) => (type === 'foo');
const FooHOC = Comp => props => <Comp ...props>Foo</Comp>;
const BarHOC = Comp => props => <Comp ...props type="bar">Bar</Comp>;
const FooOrBarHOC = branch(fooPredicate, FooHOC, BarHOC);
const SomeHOC = compose(BazHOC, FooOrBarHOC);
const SomeExampleComponent = SomeHOC(ExampleComponent);
All functions involved in SomeExampleComponent
are reusable and can be tested and used separately from each other.
In case the case is simple and these functions aren't expected to be used with any component except ExampleComponent
, it can be simplified to:
const SomeExampleComponent = BazHOC(props => (
props.type === 'foo'
? <ExampleComponent ...props>Foo</ExampleComponent>
: <ExampleComponent ...props type="bar">Bar</ExampleComponent>
));
Upvotes: 6