OptionalWrapper OptionalWrapper conditionally applies a wrapper without duplicating markup. It uses Show internally, so truthy when values render the wrapped children and falsy values render the fallback or the original children.
function OptionalWrapper<T>(props: {
when: T;
children: React.ReactNode;
wrapper: (children: React.ReactNode) => React.ReactNode;
fallback?: (children: React.ReactNode) => React.ReactNode;
}): React.ReactNode;Basic usage # Provide when and a wrapper function that receives the children and returns the wrapped result.
import { OptionalWrapper } from '@ilokesto/utilinent';
function Post({ post, withLink }) {
return (
<OptionalWrapper
when={withLink}
wrapper={(children) => <a href={`/posts/${post.id}`}>{children}</a>}
>
<h2>{post.title}</h2>
<p>{post.content}</p>
</OptionalWrapper>
);
}Custom fallback wrapper # Use fallback to return an alternate wrapper when the condition is false.
<OptionalWrapper
when={withLink}
wrapper={(children) => <a href={`/posts/${post.id}`}>{children}</a>}
fallback={(children) => <span className="muted">{children}</span>}
>
<h2>{post.title}</h2>
</OptionalWrapper>