UNPKG

components-switch

Version:

A lightweight React utility component library featuring Switch and Match for conditional rendering, inspired by SolidJS. Simplifies readable and declarative conditional logic in JSX.

1 lines 2.9 kB
{"version":3,"file":"components-switch.cjs","sources":["../src/Match.tsx","../src/utils.ts","../src/Switch.tsx"],"sourcesContent":["import { ReactNode } from \"react\";\nimport { BoolOrFn } from \"./types\";\n\nexport type MatchProps = {\n children: ReactNode;\n when: BoolOrFn;\n}\n\nexport function Match({ children }: MatchProps) {\n return children\n}\n","import { isValidElement, ReactElement, ReactNode } from \"react\";\n\nimport { BoolOrFn } from \"./types\";\nimport { Match, MatchProps } from \"./Match\";\n\nexport function isMatchElement(element: ReactNode): element is ReactElement<MatchProps, typeof Match> {\n return (\n isValidElement(element) &&\n element.type === Match &&\n \"when\" in (element.props as MatchProps)\n );\n}\n\nexport function isMatchValidCondition(condition: BoolOrFn) {\n try {\n if (condition === undefined || condition === null) {\n return false;\n }\n\n if (typeof condition === \"function\") {\n return condition();\n }\n\n return !!condition;\n } catch {\n return false;\n }\n}\n","import { isValidElement, ReactNode } from \"react\"\n\nimport { Match } from \"./Match\";\nimport { OneOrMore } from \"./types\";\nimport { isMatchElement, isMatchValidCondition } from \"./utils\";\n\nexport type SwitchProps = {\n children: OneOrMore<typeof Match>\n fallback?: ReactNode;\n}\n\nexport function Switch({children, fallback}: SwitchProps) {\n try {\n if (!Array.isArray(children)) children = [children];\n\n const childrenToShow = [];\n\n for (let i = 0; i < children.length; ++i) {\n const child = children[i];\n\n if (!isValidElement(child)) {\n continue;\n }\n \n if (isMatchElement(child) && !isMatchValidCondition(child.props.when)) {\n continue;\n }\n\n childrenToShow.push(child);\n }\n\n\n if (childrenToShow.length === 0) {\n return fallback;\n }\n\n return childrenToShow;\n } catch {\n return fallback;\n }\n}"],"names":["Match","_ref","children","isMatchValidCondition","condition","_unused","element","fallback","Array","isArray","childrenToShow","i","length","child","isValidElement","type","props","when","push"],"mappings":"gCAQgBA,EAAKC,GACjB,OAD4BA,EAARC,QAExB,CCGM,SAAUC,EAAsBC,GAClC,IACI,OAAIA,UAIqB,mBAAdA,EACAA,MAGFA,EACb,CAAE,MAAAC,GACE,QACJ,CACJ,yCChBsBJ,GAAE,IDNOK,ECMPJ,EAAQD,EAARC,SAAUK,EAAQN,EAARM,SAC9B,IACSC,MAAMC,QAAQP,KAAWA,EAAW,CAACA,IAI1C,IAFA,IAAMQ,EAAiB,GAEdC,EAAI,EAAGA,EAAIT,EAASU,SAAUD,EAAG,CACtC,IAAME,EAAQX,EAASS,GAElBG,EAAAA,eAAeD,KDbxBC,EAAcA,eAFSR,ECmBAO,IDhBvBP,EAAQS,OAASf,GACjB,SAAWM,EAAQU,QCeeb,EAAsBU,EAAMG,MAAMC,OAIhEP,EAAeQ,KAAKL,GACxB,CAGA,OAA8B,IAA1BH,EAAeE,OACRL,EAGJG,CACX,CAAE,MAAAL,GACE,OAAOE,CACX,CACJ"}