Skip to content

Instantly share code, notes, and snippets.

@xantiagoma
Created June 7, 2025 00:54
Show Gist options
  • Save xantiagoma/c967913c03bea3ef3c69d0eb202a9742 to your computer and use it in GitHub Desktop.
Save xantiagoma/c967913c03bea3ef3c69d0eb202a9742 to your computer and use it in GitHub Desktop.
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