Skip to content

Instantly share code, notes, and snippets.

@dimitrinicolas
Last active September 6, 2022 19:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save dimitrinicolas/f9d077f9a5793c6807b858b5783d6714 to your computer and use it in GitHub Desktop.
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
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;
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