React Conditional Wrapper Component

Hey everyone!

I am looking to recreate this component in rescript, but not entirely how to do so.

const ConditionalWrapper = ({ condition, wrapper, children }) => 
  condition ? wrapper(children) : children;
<ConditionalWrapper
   condition={true}
   wrapper={children => <a href={link}>{children}</a>}
>
  <Fragment>
     <h1>{brand}</h1>
   </Fragment>
</ConditionalWrapper>

Inspiration: https://blog.hackages.io/conditionally-wrap-an-element-in-react-a8b9a47fab2

Thanks in advance!

1 Like

Here’s one way:

module ConditionalWrapper = {
  @react.component
  let make = (~condition, ~wrapper, ~children) =>
    condition ? wrapper(children) : children
}

// usage:
@react.component
let make = (~link, ~brand) => {
  <ConditionalWrapper
    condition={true} wrapper={children => <a href={link}> {children} </a>}>
    <React.Fragment> <h1> {brand} </h1> </React.Fragment>
  </ConditionalWrapper>
}

3 Likes

Wow, honestly I tried this with probably too many incorrect prop type definitions making it difficult to get working.

It was really that straight forward, thanks a ton @johnj - always a huge help on here.

1 Like

That’s why I usually don’t use type annotations unless they’re necessary. The compiler can infer them better than I can most of the time. :wink:

5 Likes

Totally agree, I need to start stopping myself from being type definition happy haha :+1: