Created
September 3, 2019 13:35
-
-
Save fwojciec/e13859d184e9072cae5754aa6f61e335 to your computer and use it in GitHub Desktop.
How to build a multilingual website in Next.js #5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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