Skip to content

Commit 396b513

Browse files
committed
extract useLocaleDirection hook
1 parent 56cb735 commit 396b513

File tree

2 files changed

+22
-12
lines changed

2 files changed

+22
-12
lines changed

src/hooks/useLocaleDirection.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { useEffect } from "react"
2+
import { useRouter } from "next/router"
3+
4+
import { Lang } from "@/lib/types"
5+
6+
import { isLangRightToLeft } from "@/lib/utils/translations"
7+
8+
/**
9+
* Custom hook that sets the DOM direction based on the locale,
10+
* responding to changes in the locale without requiring refresh.
11+
*/
12+
export const useLocaleDirection = (): void => {
13+
const { locale } = useRouter()
14+
15+
useEffect(() => {
16+
const dir = isLangRightToLeft(locale as Lang) ? "rtl" : "ltr"
17+
document.documentElement.setAttribute("dir", dir)
18+
}, [locale])
19+
}

src/pages/_app.tsx

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
import { useEffect } from "react"
2-
import { useRouter } from "next/router"
31
import { appWithTranslation } from "next-i18next"
42
// ChakraProvider import updated as recommended on https://github.com/chakra-ui/chakra-ui/issues/4975#issuecomment-1174234230
53
// to reduce bundle size. Should be reverted to "@chakra-ui/react" in case on theme issues
@@ -8,10 +6,9 @@ import { extendBaseTheme } from "@chakra-ui/react"
86

97
import customTheme from "@/@chakra-ui/theme"
108

11-
import { AppPropsWithLayout, Lang } from "@/lib/types"
12-
13-
import { isLangRightToLeft } from "@/lib/utils/translations"
9+
import { AppPropsWithLayout } from "@/lib/types"
1410

11+
import { useLocaleDirection } from "@/hooks/useLocaleDirection"
1512
import { RootLayout } from "@/layouts"
1613
import { inter, mono } from "@/lib/fonts"
1714

@@ -20,13 +17,7 @@ const App = ({ Component, pageProps }: AppPropsWithLayout) => {
2017
// Use the layout defined at the page level, if available
2118
const getLayout = Component.getLayout ?? ((page) => page)
2219

23-
const { locale } = useRouter()
24-
25-
useEffect(() => {
26-
if (!document) return
27-
const dir: "rtl" | "ltr" = isLangRightToLeft(locale as Lang) ? "rtl" : "ltr"
28-
document.getElementsByTagName("html")[0].setAttribute("dir", dir)
29-
}, [locale])
20+
useLocaleDirection()
3021

3122
const theme = extendBaseTheme(customTheme)
3223

0 commit comments

Comments
 (0)