|
1 | 1 | 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); |
4 | 6 |
|
5 | 7 | let language: string = 'pt'
|
6 | 8 | let id: number = 1
|
@@ -107,8 +109,18 @@ export function t(path: string, args?: {[key: string]: string}): string {
|
107 | 109 | return translation
|
108 | 110 | }
|
109 | 111 |
|
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'>>> |
112 | 124 | ): React.ComponentType<Subtract<P, ITranslate>> {
|
113 | 125 | class TranslatedComponent extends React.Component<Subtract<P, ITranslate>> {
|
114 | 126 | public id: number | undefined
|
@@ -136,7 +148,8 @@ export default {
|
136 | 148 | setLanguage,
|
137 | 149 | setDefaultTranslations,
|
138 | 150 | setTranslations,
|
139 |
| - translate, |
| 151 | + withTranslation, |
| 152 | + useTranslation, |
140 | 153 | subscribe,
|
141 | 154 | unsubscribe,
|
142 | 155 | t,
|
|
0 commit comments