import type { ReactElement } from "react"; import { createElement, useMemo } from "react"; import { useAppContext } from "./useAppContext"; import { _getComponentCfgForStaticMarkup } from "../_getComponentCfgForStaticMarkup"; type TSSGRenderResult = ReactElement> | null; type TStaticProps = { children?: unknown; }; /** * Хук позволяет получить компонент для его рендера в режиме `SSG`. * Компонент преобразуется в элемент `div` с атрибутом и строчным JSON-конфигом, куда далее `react-dom` рендерит непосредственно компонент. * @template TProps - тип пропсов целевого React-компонента (объект с его пользовательскими полями) * @returns {TSSGRenderResult} Возвращает React-элемент-контейнер для статической разметки в режиме `SSG`, в остальных режимах возвращает `null`. * @example * import { useSSGRender } from "@delement/ui/utils/react"; * * const App = () => { * return useSSGRender( * "data-js-component", * { id: "card", children: "content" }, * "section", * "myStaticContainer" * ); * }; */ export const useSSGRender = ( attr: string, props: TProps & TStaticProps, tagName: string = "div", className: string = "staticContainer" ): TSSGRenderResult => { const { mode } = useAppContext(); return useMemo(() => { if (mode === "SSG") { const templateProps = { [attr]: _getComponentCfgForStaticMarkup(props), children: props?.children, className, }; return createElement(tagName, templateProps); } else { return null; } }, [ mode, attr, props, tagName, className ]); };