How to conditionally render reason-react component?

387 Views Asked by At

Something that has started appearing in my code quite a bit is:

<Parent>
  {if (condition) {
     <Child />;
   } else {
     <div />;
   }}
  <Sibling />
</Parent>;

Basically I only want the Child to render if the condition is true, otherwise render nothing.

It feels wrong putting the div in the else condition, since this renders a div that really shouldn't be there. How can I conditionally render a component without having to render an unnecessary element if the condition is false?

1

There are 1 best solutions below

0
BackfromHell On BEST ANSWER

You have to use React.null instead of the empty div.

ReasonML forces you to have the same type in the if and else blocks, and as you return a React.element in the if block, you also need to return one in the else block.

You can however use ternary, if you want your code to be a bit shorter:

<Parent>
  {condition ? <Child /> : React.null}
  <Sibling />
</Parent>;