Last active
March 13, 2024 12:32
-
-
Save Abdillahzakkie/336b8e566fba69833f3e38ddfe3394b6 to your computer and use it in GitHub Desktop.
React Show JSSX component
This file contains hidden or 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 React, { Children, ReactNode } from "react"; | |
| interface ShowProps { | |
| children: ReactNode; | |
| } | |
| interface ShowChildProps { | |
| when?: boolean; | |
| } | |
| export default function Show(props: ShowProps) { | |
| let when: ReactNode | null = null; | |
| let otherwise: ReactNode | null = null; | |
| Children.forEach(props.children, (children) => { | |
| if (React.isValidElement(children)) { | |
| const childProps = children.props as ShowChildProps; | |
| if (childProps.when) { | |
| when = children; | |
| } else { | |
| otherwise = children; | |
| } | |
| } | |
| }); | |
| return when || otherwise; | |
| } | |
| Show.When = ({ | |
| isTrue, | |
| children, | |
| }: { | |
| isTrue: boolean; | |
| children: React.ReactNode; | |
| }) => isTrue && children; | |
| Show.Else = ({ | |
| render, | |
| children, | |
| }: { | |
| render?: React.ReactNode; | |
| children?: React.ReactNode; | |
| }) => render || children || <></>; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment