Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why and when use recompose branch?

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

like image 913
Reza Sam Avatar asked Dec 16 '18 07:12

Reza Sam


1 Answers

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>
));
like image 188
Estus Flask Avatar answered Oct 13 '22 20:10

Estus Flask