Skip to content

Instantly share code, notes, and snippets.

@rawnly
Created April 1, 2021 15:31
Show Gist options
  • Save rawnly/78008b43233248611b592199e808f220 to your computer and use it in GitHub Desktop.
Save rawnly/78008b43233248611b592199e808f220 to your computer and use it in GitHub Desktop.
Super simple Switch case as React Functional Component
// Super simple Switch case as React Functional Component
import React, { FC, Children, ReactElement } from "react";
const Case: FC<{ value: SwitchValue } | { default: true }> = ( { children } ) =>
<>{children}</>;
const checkCondition = ( condition, value ) => {
if ( condition instanceof Function && condition( value ) ) return true;
return condition === value;
};
type SwitchValue = number | string | boolean;
type SwitchProps = {
condition: SwitchValue | ( ( value: SwitchValue ) => boolean );
ignoreDom?: boolean;
}
type SwitchComponent = FC<SwitchProps> & {
Case: FC<{ value: SwitchValue } | { default: true }>
}
const Switch: SwitchComponent = ( { children, condition, ignoreDom = true } ) => {
let defaultComponent = null;
const cases = [];
Children.forEach( children, ( child: ReactElement ) => {
const { value } = child.props;
if ( typeof child.type !== "function" ) {
if ( ignoreDom ) return;
cases.push( child );
return;
}
if ( child.props.default ) {
defaultComponent = child;
}
if ( checkCondition( condition, value ) ) {
cases.push( child );
}
} );
if ( !cases.length ) {
return defaultComponent;
}
return cases;
};
Switch.Case = Case;
export default Switch;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment