Skip to content

Instantly share code, notes, and snippets.

@erenkulaksiz
Last active June 12, 2023 06:45
Show Gist options
  • Save erenkulaksiz/21455f198c3d3bf51c71ce060da61b84 to your computer and use it in GitHub Desktop.
Save erenkulaksiz/21455f198c3d3bf51c71ce060da61b84 to your computer and use it in GitHub Desktop.
basic conditional render in react
import { Children } from "react";
import type { ViewProps, ViewIfElseProps } from "./View.types";
export default function View({ viewIf, div, children }: ViewProps) {
if (Children.count(children) > 2)
throw new Error(
"View component can only have 2 children, View.If and View.Else"
);
if (viewIf === true) return <>{Children.toArray(children)[0]}</>;
return <>{Children.toArray(children)[1]}</>;
}
function ViewIf({ children, hidden, visible }: ViewIfElseProps) {
if (typeof hidden == null && typeof visible == null) return <>{children}</>;
if (hidden === true) return <></>;
if (visible === false) return <></>;
return <>{children}</>;
}
View.If = ViewIf;
View.Else = ViewIf;
export interface ViewProps {
viewIf?: boolean;
children?: React.ReactNode;
className?: string;
div?: boolean;
hidden?: boolean;
}
export interface ViewIfElseProps {
children: React.ReactNode;
hidden?: boolean;
visible?: boolean;
}
@erenkulaksiz
Copy link
Author

usage:

<View viewIf={theme === "dark"}>
  <View.If>
    <MdDarkMode />
  </View.If>
  <View.Else>
    <MdLightMode />
  </View.Else>
</View>

@erenkulaksiz
Copy link
Author

erenkulaksiz commented Jun 12, 2023

Single usage:

<View.If visible={theme == "dark"}>
  <MdDarkMode />
</View.If>

or

<View.If hidden={theme == "light"}>
  <MdDarkMode />
</View.If>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment