From d4ad6869962cf1d260c4ee3b0e8b3e63c943bfd4 Mon Sep 17 00:00:00 2001 From: Saket Tiwari Date: Wed, 29 Oct 2025 20:50:09 +0530 Subject: [PATCH] added support for dynamic text translation in React components (Fixes #1206) --- packages/react/src/core/component.tsx | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/packages/react/src/core/component.tsx b/packages/react/src/core/component.tsx index 8d3a0533f..ed61c464e 100644 --- a/packages/react/src/core/component.tsx +++ b/packages/react/src/core/component.tsx @@ -32,17 +32,24 @@ export const LingoComponent = React.forwardRef( $expressions, ...rest } = props; - const maybeValue = $dictionary?.files?.[$fileKey]?.entries?.[$entryKey]; + // 1). try to find static translation from the dictionary + const maybeValue = $dictionary?.files?.[$fileKey]?.entries?.[$entryKey]; + + const dynamicValue = + !maybeValue && typeof $entryKey === "string" + ? autoTranslateText($entryKey, $dictionary) + : maybeValue; + const children = useMemo(() => { return _.flow([ (nodes) => ifNotEmpty(replaceElements, $elements, nodes), (nodes) => ifNotEmpty(replaceVariables, $variables, nodes), (nodes) => ifNotEmpty(replaceFunctions, $functions, nodes), (nodes) => ifNotEmpty(replaceExpressions, $expressions, nodes), - ])([maybeValue ?? $entryKey]); + ])([dynamicValue ?? $entryKey]); }, [ - maybeValue, + dynamicValue, $entryKey, $elements, $variables, @@ -65,8 +72,8 @@ export const LingoComponent = React.forwardRef( }, ); -// testValue needs to be cloned before passing to the callback for the first time only -// it can not be cloned inside the callback because it is called recursively + + function ifNotEmpty( callback: (nodes: ReactNode[], value: T) => ReactNode[], testValue: T, @@ -284,3 +291,12 @@ function replaceExpressions( return processWithIndex(nodes); } + +/* + helper for handle dynamic ( non-key ) translation text ...... +*/ +function autoTranslateText(text: string, dictionary: any): string { + const fallback = dictionary?.files?.auto?.entries?.[text]; + + return fallback || text; +}