File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change
1
+ import React , { useEffect , useState } from "react" ;
2
+ import { useTranslation } from "next-export-i18n" ;
3
+
4
+ export type TransProps = {
5
+ i18nKey : string ;
6
+ values ?: Record < string , string | number | React . ReactNode > ;
7
+ components ?: { [ key : string ] : React . ReactNode } ;
8
+ } ;
9
+
10
+ const Trans : React . FC < TransProps > = ( {
11
+ i18nKey,
12
+ values = { } ,
13
+ components = { } ,
14
+ } ) => {
15
+ const { t } = useTranslation ( ) ;
16
+ const [ mounted , setMounted ] = useState ( false ) ;
17
+
18
+ useEffect ( ( ) => {
19
+ setMounted ( true ) ;
20
+ } , [ ] ) ;
21
+
22
+ if ( ! mounted ) return null ;
23
+
24
+ const translation = t ( i18nKey ) ;
25
+
26
+ const renderWithPlaceholders = ( template : string ) => {
27
+ const parts = template . split ( / ( { { \s * .* ?\s * } } ) / g) ; // Split on placeholders like {{key}}
28
+
29
+ return parts . map ( ( part , index ) => {
30
+ const match = part . match ( / ^ { { \s * ( .* ?) \s * } } $ / ) ;
31
+ if ( match ) {
32
+ const key = match [ 1 ] ;
33
+ if ( key in values ) {
34
+ const value = values [ key ] ;
35
+ return < React . Fragment key = { `val-${ index } ` } > { value } </ React . Fragment > ;
36
+ } else if ( key in components ) {
37
+ return (
38
+ < React . Fragment key = { `comp-${ index } ` } >
39
+ { components [ key ] }
40
+ </ React . Fragment >
41
+ ) ;
42
+ } else {
43
+ // Return raw placeholder if key not found
44
+ return part ;
45
+ }
46
+ }
47
+ return < React . Fragment key = { `txt-${ index } ` } > { part } </ React . Fragment > ;
48
+ } ) ;
49
+ } ;
50
+
51
+ return < > { renderWithPlaceholders ( translation ) } </ > ;
52
+ } ;
53
+
54
+ export default Trans ;
You can’t perform that action at this time.
0 commit comments