Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/rude-dragons-buy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@refinedev/react-router": patch
"@refinedev/core": patch
---

- add i18n namespace option directly to useTranslation, useTranslate, useDocumentTitle hooks.
18 changes: 18 additions & 0 deletions documentation/docs/i18n/i18n-provider/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,24 @@ const title = translate("posts.fields.title", { ns: "resources" }, "Title");
// ...
```

- Example using namespace option

Using the `ns` option in the hook initializer sets a default namespace for all translations:

```tsx
import { useTranslation } from "@refinedev/core";

// ...

const { translate } = useTranslation({ ns: "resources" });

// ...

const title = translate("posts.fields.title", "Title");

// ...
```

You can use the [`useTranslation`][use-translation] hook to call `translate` method.

### changeLocale
Expand Down
37 changes: 37 additions & 0 deletions packages/core/src/hooks/i18n/useTranslate.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as React from "react";
import { vi } from "vitest";

import { useTranslate } from "@hooks";
import { TestWrapper, render } from "@test";
Expand Down Expand Up @@ -46,4 +47,40 @@ describe("useTranslate", () => {

expect(getByText("merhaba test")).toBeTruthy();
});

it("passes ns with options to i18nProvider", () => {
const translateMock = vi.fn(() => "hello");

const TestNsComponent = () => {
const translate = useTranslate({ ns: "common" });

return (
<div>
{translate(
"products.title.key",
{ option1: "option1" },
"fallback-title",
)}
</div>
);
};

const { getByText } = render(<TestNsComponent />, {
wrapper: TestWrapper({
resources: [{ name: "products" }],
i18nProvider: {
translate: translateMock,
changeLocale: () => Promise.resolve(),
getLocale: () => "en",
},
}),
});

expect(getByText("hello")).toBeTruthy();
expect(translateMock).toHaveBeenCalledWith(
"products.title.key",
{ ns: "common", option1: "option1" },
"fallback-title",
);
});
});
23 changes: 18 additions & 5 deletions packages/core/src/hooks/i18n/useTranslate.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { useContext, useMemo } from "react";

import { I18nContext } from "@contexts/i18n";
import type { UseTranslationProps } from "./useTranslation";

/**
* If you need to translate the texts in your own components, refine provides the `useTranslate` hook.
* It returns the translate method from `i18nProvider` under the hood.
*
* @see {@link https://refine.dev/docs/api-reference/core/hooks/translate/useTranslate} for more details.
*/
export const useTranslate = () => {
export const useTranslate = ({ ns }: UseTranslationProps = {}) => {
const { i18nProvider } = useContext(I18nContext);

const fn = useMemo(() => {
Expand All @@ -21,14 +22,26 @@ export const useTranslate = () => {

function translate(
key: string,
options?: string | any,
defaultMessage?: string,
_options?: string | any,
_defaultMessage?: string,
) {
let options = _options;
let defaultMessage = _defaultMessage;

if (typeof options === "string" && defaultMessage === undefined) {
options = undefined;
defaultMessage = options;
}

if (ns && options && typeof options !== "string") {
options = { ns, ...options };
}

return (
i18nProvider?.translate(key, options, defaultMessage) ??
defaultMessage ??
(typeof options === "string" && typeof defaultMessage === "undefined"
? options
(typeof _options === "string" && typeof _defaultMessage === "undefined"
? _options
: key)
);
}
Expand Down
36 changes: 36 additions & 0 deletions packages/core/src/hooks/i18n/useTranslation.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,40 @@ describe("useTranslation", () => {
expect(changeLocale).toHaveBeenCalledTimes(1);
expect(changeLocale).toHaveBeenCalledWith("en");
});

it("should pass ns option to translate", () => {
const translateMock = vi.fn();

const TestComponentWithNs: React.FC = () => {
const { translate } = useTranslation({ ns: "common" });

return (
<div>
{translate(
"products.title.key",
{ opiton1: "option1" },
"fallback-title",
)}
</div>
);
};

render(<TestComponentWithNs />, {
wrapper: TestWrapper({
resources: [{ name: "products" }],
i18nProvider: {
translate: translateMock,
changeLocale: vi.fn(),
getLocale: vi.fn(),
},
}),
});

expect(translateMock).toHaveBeenCalledTimes(1);
expect(translateMock).toHaveBeenCalledWith(
"products.title.key",
{ ns: "common", opiton1: "option1" },
"fallback-title",
);
});
});
8 changes: 6 additions & 2 deletions packages/core/src/hooks/i18n/useTranslation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ import { useGetLocale } from "./useGetLocale";
import { useSetLocale } from "./useSetLocale";
import { useTranslate } from "./useTranslate";

export interface UseTranslationProps {
ns?: string | string[];
}

/**
* It combines `useTranslate`, `useSetLocale` and `useGetLocale` hooks for a better developer experience.
* It returns `i18nProvider` methods under the hood.
Expand All @@ -11,8 +15,8 @@ import { useTranslate } from "./useTranslate";
*
* @see {@link https://refine.dev/docs/i18n/i18n-provider/} for more details.
*/
export const useTranslation = () => {
const translate = useTranslate();
export const useTranslation = ({ ns }: UseTranslationProps = {}) => {
const translate = useTranslate({ ns });
const changeLocale = useSetLocale();
const getLocale = useGetLocale();

Expand Down
41 changes: 26 additions & 15 deletions packages/react-router/src/use-document-title.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,37 @@
import { useTranslate } from "@refinedev/core";
import { useEffect } from "react";
import { useTranslate, type UseTranslationProps } from "@refinedev/core";
import { useCallback, useEffect } from "react";

type Title = string | { i18nKey: string };

export const useDocumentTitle = (title?: Title) => {
const translate = useTranslate();
interface useDocumentTitleOptions {
ns?: UseTranslationProps["ns"];

/**
* Passed to defaultMessage for translate from useTranslate
*/
defaultTitle?: string;
}

export const useDocumentTitle = (
title?: Title,
options?: useDocumentTitleOptions,
) => {
const translate = useTranslate({ ns: options?.ns });

const getTitleCB = (title: Title) => {
const key = typeof title === "string" ? title : title.i18nKey;

return translate(key, options?.defaultTitle);
};
const getTitle = useCallback(getTitleCB, [translate, options?.defaultTitle]);

useEffect(() => {
if (!title) return;

if (typeof title === "string") {
document.title = translate(title);
} else {
document.title = translate(title.i18nKey);
}
}, [title]);
document.title = getTitle(title);
}, [title, getTitle]);

return (title: Title) => {
if (typeof title === "string") {
document.title = translate(title);
} else {
document.title = translate(title.i18nKey);
}
document.title = getTitle(title);
};
};
Loading