Skip to content

Commit c559bc3

Browse files
author
joaogsleite
committed
added useTranslation hook
1 parent 512a7dc commit c559bc3

File tree

1 file changed

+18
-5
lines changed

1 file changed

+18
-5
lines changed

src/index.tsx

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import hoistStatics from 'hoist-non-react-statics'
2-
import React from 'react'
3-
import { Subtract } from 'utility-types'
2+
import React, { useEffect, useState } from 'react'
3+
import { SetDifference, Subtract } from 'utility-types'
4+
5+
const useForceUpdate = () => () => useState()[1](undefined);
46

57
let language: string = 'pt'
68
let id: number = 1
@@ -107,8 +109,18 @@ export function t(path: string, args?: {[key: string]: string}): string {
107109
return translation
108110
}
109111

110-
export function translate<P extends ITranslate>(
111-
Component: React.ComponentType<P>
112+
export function useTranslation(basePath?: string) {
113+
const forceUpdate = useForceUpdate()
114+
useEffect(() => {
115+
const subId = subscribe(() => forceUpdate())
116+
return () => unsubscribe(subId)
117+
}, [forceUpdate])
118+
return (path: string, args?: {[key: string]: string}) =>
119+
t(basePath ? (basePath + '.' + path) : path, args)
120+
}
121+
122+
export function withTranslation<P extends ITranslate>(
123+
Component: React.ComponentType<Pick<P, SetDifference<keyof P, 't'>>>
112124
): React.ComponentType<Subtract<P, ITranslate>> {
113125
class TranslatedComponent extends React.Component<Subtract<P, ITranslate>> {
114126
public id: number | undefined
@@ -136,7 +148,8 @@ export default {
136148
setLanguage,
137149
setDefaultTranslations,
138150
setTranslations,
139-
translate,
151+
withTranslation,
152+
useTranslation,
140153
subscribe,
141154
unsubscribe,
142155
t,

0 commit comments

Comments
 (0)