Last active
September 6, 2022 19:06
-
-
Save dimitrinicolas/f9d077f9a5793c6807b858b5783d6714 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