11import { useContext , useMemo } from "react" ;
22
33import { I18nContext } from "@contexts/i18n" ;
4+ import type { UseTranslationProps } from "./useTranslation" ;
45
56/**
67 * If you need to translate the texts in your own components, refine provides the `useTranslate` hook.
78 * It returns the translate method from `i18nProvider` under the hood.
89 *
910 * @see {@link https://refine.dev/docs/api-reference/core/hooks/translate/useTranslate } for more details.
1011 */
11- export const useTranslate = ( ) => {
12+ export const useTranslate = ( { ns } : UseTranslationProps = { } ) => {
1213 const { i18nProvider } = useContext ( I18nContext ) ;
1314
1415 const fn = useMemo ( ( ) => {
@@ -21,20 +22,37 @@ export const useTranslate = () => {
2122
2223 function translate (
2324 key : string ,
24- options ?: string | any ,
25- defaultMessage ?: string ,
25+ _options ?: string | any ,
26+ _defaultMessage ?: string ,
2627 ) {
28+ let options = _options ;
29+ let defaultMessage = _defaultMessage ;
30+
31+ if ( typeof options === "string" && defaultMessage === undefined ) {
32+ defaultMessage = options ;
33+
34+ if ( ns ) {
35+ options = { ns } ;
36+ } else {
37+ options = undefined ;
38+ }
39+ }
40+
41+ if ( ns && options && typeof options !== "string" ) {
42+ options = { ns, ...options } ;
43+ }
44+
2745 return (
2846 i18nProvider ?. translate ( key , options , defaultMessage ) ??
2947 defaultMessage ??
30- ( typeof options === "string" && typeof defaultMessage === "undefined"
31- ? options
48+ ( typeof _options === "string" && typeof _defaultMessage === "undefined"
49+ ? _options
3250 : key )
3351 ) ;
3452 }
3553
3654 return translate ;
37- } , [ i18nProvider ] ) ;
55+ } , [ i18nProvider , ns ] ) ;
3856
3957 return fn ;
4058} ;
0 commit comments