UNPKG

ra-core

Version:

Core components of react-admin, a frontend Framework for building admin applications on top of REST services, using ES6, React

38 lines 1.72 kB
import React, { isValidElement } from 'react'; import { useTranslate } from "./useTranslate.js"; const SPLIT_MARKER = '#@RA_CORE_INTERNAL_SPLIT@#'; export const Translate = ({ i18nKey, options, children }) => { const translate = useTranslate(); // Separate React element values from plain values const elementMap = {}; const sanitizedOptions = {}; let placeholderIndex = 0; if (options) { for (const [key, value] of Object.entries(options)) { if (isValidElement(value)) { const placeholder = `TRANSLATION_PLACEHOLDER_${placeholderIndex++}`; elementMap[placeholder] = value; sanitizedOptions[key] = `${SPLIT_MARKER}${placeholder}${SPLIT_MARKER}`; } else { sanitizedOptions[key] = value; } } } const translateOptions = typeof children === 'string' ? { _: children, ...sanitizedOptions } : sanitizedOptions; const translatedMessage = translate(i18nKey, translateOptions); if (!translatedMessage) { return children; } // If no elements were extracted, return plain string if (placeholderIndex === 0) { return React.createElement(React.Fragment, null, translatedMessage); } // Split the translated string and replace placeholders with React elements const parts = translatedMessage.split(SPLIT_MARKER); return (React.createElement(React.Fragment, null, parts.map((part, index) => index % 2 === 1 ? (React.createElement(React.Fragment, { key: index }, elementMap[part])) : (React.createElement(React.Fragment, { key: index }, part))))); }; //# sourceMappingURL=Translate.js.map