Skip to content

Instantly share code, notes, and snippets.

@serifcolakel
Created September 24, 2023 12:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save serifcolakel/3c1de389f010a3ed182bcc992862bfd4 to your computer and use it in GitHub Desktop.
Save serifcolakel/3c1de389f010a3ed182bcc992862bfd4 to your computer and use it in GitHub Desktop.
/* eslint-disable react/jsx-no-useless-fragment */
import React, { type ReactNode } from 'react';
/**
* @description A component that conditionally renders its children based on a given condition and optional limit.
*/
interface ConditionalRenderProps {
/**
* @description The condition to render the children.
* @default false
*/
condition: boolean;
/**
* @description The children to render.
* @default null
*/
children: ReactNode;
/**
* @description The maximum number of children to render.
* @default undefined
* @remarks If the limit is 0, then it will not render any children. Otherwise, it will render up to the specified limit if the condition is true.
*/
limit?: number;
}
function If({ children, condition, limit }: ConditionalRenderProps) {
if (limit !== undefined && limit <= 0) {
return null;
}
// eslint-disable-next-line react/jsx-fragments
return condition ? <React.Fragment>{children}</React.Fragment> : null;
}
function Else({ condition, ...rest }: ConditionalRenderProps) {
return If({ condition: !condition, ...rest });
}
/**
* @description Renders children if condition is true, otherwise null
* @param condition The condition to render children
* @param children The children to render
* @param limit The limit to render children
* @returns The children if condition is true, otherwise null
*/
function ConditionalRender({
condition,
children,
limit,
}: ConditionalRenderProps) {
return (
<If condition={condition} limit={limit}>
{children}
</If>
);
}
ConditionalRender.If = If;
ConditionalRender.Else = Else;
ConditionalRender.defaultProps = {
limit: undefined,
};
export default ConditionalRender;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment