Skip to content

Instantly share code, notes, and snippets.

@bruno-brant
Created July 21, 2021 16:24
Show Gist options
  • Save bruno-brant/4a4257af69f1331ab1493664a2ca52d5 to your computer and use it in GitHub Desktop.
Save bruno-brant/4a4257af69f1331ab1493664a2ca52d5 to your computer and use it in GitHub Desktop.
SwitchCase for JSX
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