Last active
June 12, 2023 06:45
-
-
Save erenkulaksiz/21455f198c3d3bf51c71ce060da61b84 to your computer and use it in GitHub Desktop.
basic conditional render in react
This file contains 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 { 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; |
This file contains 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
export interface ViewProps { | |
viewIf?: boolean; | |
children?: React.ReactNode; | |
className?: string; | |
div?: boolean; | |
hidden?: boolean; | |
} | |
export interface ViewIfElseProps { | |
children: React.ReactNode; | |
hidden?: boolean; | |
visible?: boolean; | |
} |
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
usage: