Skip to main content

IfElse

The IfElse component is a simple utility that renders one of two components based on a given condition. It accepts a condition prop to specify the condition — renders truthyComponent when the condition is true, and falsyComponent when it is false.

The condition prop accepts not only a plain boolean value, but also a function that returns a boolean. In that case, the component calls the function to evaluate the condition.


Code

🔗 View source code


Interface

typescript
type Condition = boolean | (() => boolean);

interface IfElseProps {
condition: Condition;
truthyComponent: React.ReactNode;
falsyComponent: React.ReactNode;
}

const IfElse: ({
condition,
truthyComponent,
falsyComponent,
}: IfElseProps) => JSX.Element;

Props

NameTypeDefaultDescription
conditionboolean | (() => boolean)-The condition for rendering
truthyComponentReact.ReactNode-Component rendered when condition is true
falsyComponentReact.ReactNode-Component rendered when condition is false

Usage

typescript
import { IfElse } from '@modern-kit/react';

const Example = () => {
const [state, setState] = useState<boolean>(false);
return (
<>
<button onClick={() => setState(!state)}>Toggle Button</button>
<IfElse
condition={state}
truthyComponent={<h1>true component</h1>}
falsyComponent={<h1>false component</h1>}
/>
</>
);
}

Example

false component