Created
August 16, 2023 15:58
-
-
Save ledbetterljoshua/b9f0f5565581aa7908d375c9b7028d67 to your computer and use it in GitHub Desktop.
react conditional component
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 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