Skip to content

Instantly share code, notes, and snippets.

@Abdillahzakkie
Last active March 13, 2024 12:32
Show Gist options
  • Select an option

  • Save Abdillahzakkie/336b8e566fba69833f3e38ddfe3394b6 to your computer and use it in GitHub Desktop.

Select an option

Save Abdillahzakkie/336b8e566fba69833f3e38ddfe3394b6 to your computer and use it in GitHub Desktop.
React Show JSSX component
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