Created
September 24, 2023 12:51
-
-
Save serifcolakel/3c1de389f010a3ed182bcc992862bfd4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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