Created
July 21, 2021 16:24
-
-
Save bruno-brant/4a4257af69f1331ab1493664a2ca52d5 to your computer and use it in GitHub Desktop.
SwitchCase for JSX
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"; | |
export class Case extends React.Component<{ value: Number | String | Boolean }> { | |
render() { | |
return <>{this.props.children}</>; | |
} | |
} | |
export interface SwitchProps { | |
value: number | boolean | string; | |
children: React.ReactElement[]; | |
} | |
/** | |
* Component that display a single child based on a value. | |
* @param param0 Properties of the children. | |
* @param param0.value The value the switch is using to decide which child to show. | |
*/ | |
export function Switch({ value, children }: SwitchProps) { | |
const childMap: { [key: string]: React.ReactElement[] } = {}; | |
for (const child of children) { | |
if (!child.props) continue; | |
childMap[child.props.value] = child.props.children; | |
} | |
return <>{childMap[String(value)]}</>; | |
} | |
const SwitchCase = { | |
Switch, | |
Case, | |
}; | |
export default SwitchCase; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment