React components for clean, declarative conditional rendering with async support
npx @tessl/cli install tessl/npm-react-if@4.1.0React If provides clean, declarative components for conditional rendering in React applications. It replaces verbose ternary operators and complex conditional logic with readable, expressive JSX components that support both synchronous conditions and asynchronous Promise-based conditions.
npm install react-ifimport { If, Then, Else, When, Unless, Switch, Case, Default, Fallback } from "react-if";For CommonJS:
const { If, Then, Else, When, Unless, Switch, Case, Default, Fallback } = require("react-if");import { If, Then, Else, When, Unless } from "react-if";
const UserProfile = ({ user, isLoggedIn, age, drinkingAge }) => (
<div>
{/* Basic conditional rendering */}
<If condition={isLoggedIn}>
<Then>
<span>Welcome, {user.name}!</span>
</Then>
<Else>
<span>Please log in</span>
</Else>
</If>
{/* Shorthand for simple conditions */}
<When condition={age >= drinkingAge}>
<span>You can have a beer!</span>
</When>
<Unless condition={user.isVerified}>
<div className="warning">Please verify your account</div>
</Unless>
</div>
);React If is built around several key design patterns:
Core If/Then/Else pattern for standard conditional rendering scenarios. Provides clear alternatives to ternary operators.
const If: FC<{
condition: BooleanLike | (() => BooleanLike);
keepAlive?: boolean;
children: ReactNode;
}>;
const Then: FC<{ children?: ReactNode | (() => JSX.Element) }>;
const Else: FC<{ children?: ReactNode | (() => JSX.Element) }>;Multi-condition branching similar to switch statements, with support for multiple Cases and a Default fallback.
const Switch: FC<{ children: ReactNode }>;
const Case: FC<{
condition: BooleanLike | (() => BooleanLike);
children?: ReactNode | (() => JSX.Element);
}>;
const Default: FC<{ children?: ReactNode | (() => JSX.Element) }>;Simplified components for common single-condition scenarios without the need for explicit Then/Else blocks.
const When: FC<{
condition: BooleanLike | (() => BooleanLike);
children?: ReactNode | (() => JSX.Element);
}>;
const Unless: FC<{
condition: BooleanLike | (() => BooleanLike);
children?: ReactNode | (() => JSX.Element);
}>;Promise-based conditional rendering with loading states, error handling, and promise cancellation support.
const If: FC<{
condition: Promise<any>;
keepAlive?: boolean;
children: ReactNode;
}>;
const Fallback: FC<{ children?: ReactNode | (() => JSX.Element) }>;type BooleanLike = boolean | string | number | null | undefined | ExtendablePromise<any>;
interface ExtendablePromise<T> extends Promise<T> {
[index: string]: any;
}
interface CancellablePromise {
promise: ExtendablePromise<any>;
cancel: () => void;
}
type ComponentWithConditionProps<P = {}> = P & PropsWithChildren<{
condition: (() => BooleanLike) | BooleanLike;
}>;
interface AsyncSupportProps {
keepAlive?: boolean;
}