Skip to content

Instantly share code, notes, and snippets.

@ledbetterljoshua
Created August 16, 2023 15:58
Show Gist options
  • Save ledbetterljoshua/b9f0f5565581aa7908d375c9b7028d67 to your computer and use it in GitHub Desktop.
Save ledbetterljoshua/b9f0f5565581aa7908d375c9b7028d67 to your computer and use it in GitHub Desktop.
react conditional component
import React from "react";
const Case = ({ children }) => children;
const Default = ({ children }) => children;
const Switch = ({ children }) => {
let matchChild = null;
let defaultCase = null;
React.Children.forEach(children, (child) => {
if (!matchChild && child.type === Case) {
const { condition } = child.props;
const conditionalResult = Boolean(condition);
if (conditionalResult) {
matchChild = child;
}
} else if (!defaultCase && child.type === Default) {
defaultCase = child;
}
});
return matchChild ?? defaultCase ?? null;
};
export { Case, Default, Switch };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment