Skip to content

Instantly share code, notes, and snippets.

@fwojciec
Created September 3, 2019 13:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fwojciec/e13859d184e9072cae5754aa6f61e335 to your computer and use it in GitHub Desktop.
Save fwojciec/e13859d184e9072cae5754aa6f61e335 to your computer and use it in GitHub Desktop.
How to build a multilingual website in Next.js #5
// hocs/withLocale.tsx
import React from 'react'
import { NextPage } from 'next'
import Error from 'next/error'
import { getDisplayName } from 'next-server/dist/lib/utils'
import { isLocale, Locale } from '../translations/types'
import { LocaleProvider } from '../context/LocaleContext'
interface LangProps {
locale?: Locale
}
export default (WrappedPage: NextPage<any>) => {
const WithLocale: NextPage<any, LangProps> = ({ locale, ...pageProps }) => {
if (!locale) {
// no valid locale detected
return <Error statusCode={404} />
}
return (
<LocaleProvider lang={locale}>
<WrappedPage {...pageProps} />
</LocaleProvider>
)
}
WithLocale.getInitialProps = async ctx => {
// retrieve initial props of the wrapped component
let pageProps = {}
if (WrappedPage.getInitialProps) {
pageProps = await WrappedPage.getInitialProps(ctx)
}
if (typeof ctx.query.lang !== 'string' || !isLocale(ctx.query.lang)) {
// in case the value of 'lang' is not a valid locale return it as undefined
return { ...pageProps, locale: undefined }
}
// the locale is valid
return { ...pageProps, locale: ctx.query.lang }
}
// pretty display name for the debugger
WithLocale.displayName = `withLang(${getDisplayName(WrappedPage)})`
return WithLocale
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment