Created
June 7, 2025 00:54
-
-
Save xantiagoma/c967913c03bea3ef3c69d0eb202a9742 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import { ReactNode } from 'react'; | |
/** | |
* Component that conditionally renders children based on a value | |
* @param props.value - Value to check | |
* @param props.children - Content to render, either direct ReactNode or function that receives the value | |
* @param props.condition - Optional custom condition function | |
* @returns Rendered children or null | |
* @example | |
* <When value={user}> | |
* {user => <div>Welcome {user.name}</div>} | |
* </When> | |
*/ | |
export function When<T>(props: { | |
value: T; | |
children?: ((value: NonNullable<T>) => ReactNode) | ReactNode; | |
condition?: (value: T, defaultCheck?: (value: T) => boolean) => boolean; | |
}): ReactNode { | |
const defaultCheck = (value: T) => value != null && value !== false; | |
const { value, children, condition = defaultCheck } = props; | |
if (!condition(value, defaultCheck)) { | |
return null; | |
} | |
return typeof children === 'function' | |
? children(value as NonNullable<T>) | |
: children; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment