Skip to content

Commit

Permalink
Auto serve translated pages (#430)
Browse files Browse the repository at this point in the history
  • Loading branch information
viphan007 authored Sep 20, 2024
1 parent bb26492 commit 1222848
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 193 deletions.
1 change: 0 additions & 1 deletion src/components/Header.js
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,6 @@ const StyledHeader = props => {
const localizedPath = getLocalizedPath(pathname, locale.code)

setLocalStorage('preferredLanguage', locale.code)
setLocalStorage('locale-opt-out', true)

window.location.replace(localizedPath)
}
Expand Down
190 changes: 0 additions & 190 deletions src/components/LocaleSwitcherBanner.js

This file was deleted.

32 changes: 32 additions & 0 deletions src/hooks/useLocalization.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { useContext, useEffect } from 'react'
import { getLocalizedPath, LOCALES } from '../lib/config.mjs'
import { useLocation } from '@reach/router'
import { navigate } from 'gatsby'
import useLangDetect from '../hooks/useLangDetect'
import ContextClientSide from '../Context/ContextClientSide'

const useLocalization = translation => {
const detectedLang = useLangDetect()

const { localization } = useContext(ContextClientSide)
const { locale, setLocale } = localization || {}

const location = useLocation()
const { pathname } = location

useEffect(() => {
const storedLanguage = LOCALES.find(f => f.code === detectedLang?.code)

if (storedLanguage && storedLanguage.code !== locale.code) {
setLocale(storedLanguage)

if (translation) {
const localizedPath = getLocalizedPath(pathname, storedLanguage.code)

navigate(localizedPath, { replace: true })
}
}
}, [detectedLang, translation, locale, pathname])
}

export default useLocalization
4 changes: 2 additions & 2 deletions src/templates/PageLayout.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
darkDarkTheme,
defaultDarkTheme,
} from '../lib/theme'
import LocaleSwitcherBanner from '../components/LocaleSwitcherBanner'
import useLocalization from '../hooks/useLocalization'

/**
* @name PageLayout
Expand Down Expand Up @@ -95,6 +95,7 @@ const PageLayout = props => {
}

useAllClicks()
useLocalization(translation)

useEffect(() => {
if (document) {
Expand Down Expand Up @@ -153,7 +154,6 @@ const PageLayout = props => {
}}
/>
)}
{translation && <LocaleSwitcherBanner />}
</Layout>
</Context.Provider>
)
Expand Down

0 comments on commit 1222848

Please sign in to comment.