-
-
Save erkanerbay/c51dbb55f2736f7281cc37aff0055318 to your computer and use it in GitHub Desktop.
Custom Next.js Document for basic html "lang" property setting according to the page path
This file contains hidden or 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
import Document, { Head, Main, NextScript } from 'next/document'; | |
import React from 'react'; | |
const LANGUAGES = ['fr', 'en']; | |
class MyDocument extends Document { | |
render() { | |
const pathPrefix = this.props.__NEXT_DATA__.page.split('/')[1]; | |
const lang = | |
LANGUAGES.indexOf(pathPrefix) !== -1 ? pathPrefix : LANGUAGES[0]; | |
return ( | |
<html lang={lang}> | |
<Head /> | |
<body> | |
<Main /> | |
<NextScript /> | |
</body> | |
</html> | |
); | |
} | |
} | |
export default MyDocument; |
This file contains hidden or 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
import React, { useEffect } from 'react'; | |
import { withRouter } from 'next/router'; | |
const LANGUAGES = ['fr', 'en']; | |
export const Layout = withRouter( | |
({ router, children }) => { | |
useEffect(() => { | |
const pathPrefix = router.pathname.split('/')[1]; | |
const lang = | |
LANGUAGES.indexOf(pathPrefix) !== -1 ? pathPrefix : LANGUAGES[0]; | |
document.documentElement.setAttribute('lang', lang); | |
}, []); | |
return ( | |
<> | |
{children} | |
</> | |
); | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment