Replies: 3 comments
-
Hello @mi5ha , import React from "react"
import Language from "../components/language"
export default function HomePage({ pageContext: { originalPath } }) {
return (
<>
<Language originalPath={originalPath} />
</>
)
} |
Beta Was this translation helpful? Give feedback.
-
Hello again :) import React from "react"
import { useLocalization, LocalizedLink } from "gatsby-theme-i18n"
export default function LanguageSwitcher() {
const { locale, config } = useLocalization()
// set original path
let path = typeof window !== "undefined" ? window.location.pathname : ""
config.forEach(item => (path = path.replace(`${item.code}/`, "")))
return (
<div>
{config.map(lang => (
<LocalizedLink to={path} key={lang.code} language={lang.code}>
{lang.code.toUpperCase()}
</LocalizedLink>
))}
</div>
)
} |
Beta Was this translation helpful? Give feedback.
-
There is more than one way to do it, of course. Here a version adapted from gatsby-plugin-intl: const buildLocalizedLink = (code) => {
if (typeof window === "undefined") {
return
}
const removePrefix = pathname => {
const base =
typeof __BASE_PATH__ !== `undefined` ? __BASE_PATH__ : __PATH_PREFIX__
if (base && pathname.indexOf(base) === 0) {
pathname = pathname.slice(base.length)
}
return pathname
}
const removeLocalePart = pathname => {
const i = pathname.indexOf(`/`, 1)
// return '' in case we are at the root of the language, e.g. '/en'
return i < 0 ? '' : pathname.substring(i)
}
const pathname = removeLocalePart(removePrefix(window.location.pathname))
return `/${code}${pathname}${window.location.search}`
}
const changeLocale = (code) => {
const link = buildLocalizedLink(code)
navigate(link, {replace: true});
} With |
Beta Was this translation helpful? Give feedback.
-
This returns localized version:
This non localized version of the current path is necessary when language switchers are created for example.
Thank you!
Beta Was this translation helpful? Give feedback.
All reactions