UNPKG

react-intlayer

Version:

Easily internationalize i18n your React applications with type-safe multilingual content management.

1 lines 3.03 kB
{"version":3,"file":"renderReactElement.cjs","names":["element","childrenResult: ReactNode[]"],"sources":["../../../src/reactElement/renderReactElement.ts"],"sourcesContent":["import { createElement, type ReactElement, type ReactNode } from 'react';\n\n// This function recursively creates React elements from a given JSON-like structure\nexport const renderReactElement = (element: ReactElement<any>) => {\n if (typeof element === 'string') {\n // If it's a string, simply return it (used for text content)\n return element;\n }\n\n const convertChildrenAsArray = (\n element: ReactElement<{ children?: ReactNode }>\n ): ReactElement<{ children?: ReactNode }> => {\n if (element?.props && typeof element.props.children === 'object') {\n const childrenResult: ReactNode[] = [];\n const { children } = element.props;\n\n // Create the children elements recursively, if any\n Object.keys(children ?? {}).forEach((key) => {\n const childElement = renderReactElement(\n children?.[\n key as keyof typeof children\n ] as unknown as ReactElement<any>\n );\n\n // Add key prop if the child is a React element\n if (\n typeof childElement === 'object' &&\n childElement !== null &&\n 'type' in childElement\n ) {\n childrenResult.push(\n createElement(\n childElement.type,\n { ...childElement.props, key },\n ...(Array.isArray(childElement.props?.children)\n ? childElement.props.children\n : [childElement.props?.children])\n )\n );\n } else {\n childrenResult.push(childElement);\n }\n });\n\n return {\n ...element,\n props: { ...element.props, children: childrenResult },\n };\n }\n\n return {\n ...element,\n props: { ...element.props, children: element.props?.children ?? [] },\n };\n };\n\n const fixedElement = convertChildrenAsArray(\n element as ReactElement<{ children?: ReactNode }>\n );\n\n const { type, props } = fixedElement;\n\n // Create and return the React element\n return createElement(\n type ?? 'span',\n props,\n ...(props.children as ReactNode[])\n );\n};\n"],"mappings":";;;;AAGA,MAAa,sBAAsB,YAA+B;AAChE,KAAI,OAAO,YAAY,SAErB,QAAO;CAGT,MAAM,0BACJ,cAC2C;AAC3C,MAAIA,WAAS,SAAS,OAAOA,UAAQ,MAAM,aAAa,UAAU;GAChE,MAAMC,iBAA8B,EAAE;GACtC,MAAM,EAAE,aAAaD,UAAQ;AAG7B,UAAO,KAAK,YAAY,EAAE,CAAC,CAAC,SAAS,QAAQ;IAC3C,MAAM,eAAe,mBACnB,WACE,KAEH;AAGD,QACE,OAAO,iBAAiB,YACxB,iBAAiB,QACjB,UAAU,aAEV,gBAAe,8BAEX,aAAa,MACb;KAAE,GAAG,aAAa;KAAO;KAAK,EAC9B,GAAI,MAAM,QAAQ,aAAa,OAAO,SAAS,GAC3C,aAAa,MAAM,WACnB,CAAC,aAAa,OAAO,SAAS,CACnC,CACF;QAED,gBAAe,KAAK,aAAa;KAEnC;AAEF,UAAO;IACL,GAAGA;IACH,OAAO;KAAE,GAAGA,UAAQ;KAAO,UAAU;KAAgB;IACtD;;AAGH,SAAO;GACL,GAAGA;GACH,OAAO;IAAE,GAAGA,UAAQ;IAAO,UAAUA,UAAQ,OAAO,YAAY,EAAE;IAAE;GACrE;;CAOH,MAAM,EAAE,MAAM,UAJO,uBACnB,QACD;AAKD,iCACE,QAAQ,QACR,OACA,GAAI,MAAM,SACX"}