Skip to content

Instantly share code, notes, and snippets.

@Tim-W-James
Created October 17, 2023 01:35
Show Gist options
  • Select an option

  • Save Tim-W-James/9c65f40dbad1302591cc0f150ac087ae to your computer and use it in GitHub Desktop.

Select an option

Save Tim-W-James/9c65f40dbad1302591cc0f150ac087ae to your computer and use it in GitHub Desktop.
React ConditionalWrapper
type ConditionalWrapperProps = {
/**
* Inner component to be wrapped.
*/
children: React.ReactElement;
/**
* Condition to be met for the wrapper to be applied.
*/
condition: boolean;
/**
* Wrapper component to be rendered depending on the condition.
*/
wrapper: (children: React.ReactElement) => JSX.Element;
};
/**
* Conditionally wraps children in a wrapper component.
*
* @example
* ```tsx
* <ConditionalWrapper
* condition={condition}
* wrapper={(children) => <Wrapper>{children}</Wrapper>}
* >
* <Children />
* </ConditionalWrapper>
* ```
*/
export const ConditionalWrapper: React.FC<ConditionalWrapperProps> = ({
condition,
wrapper,
children,
}) => (condition ? wrapper(children) : children);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment