Reputation: 325
I want to set the <html lang="...">
tag on a NextJs application with object notation.
Im rendering a serverStylesheet for Styled-components so my current _document
file looks like this:
class CustomDocument extends Document {
static getInitialProps = async (ctx) => {
const sheet = new ServerStyleSheet();
const originalRenderPage = ctx.renderPage;
try {
ctx.renderPage = () => originalRenderPage({
enhanceApp: App => props => sheet.collectStyles(<App {...props} />),
});
const initialProps = await Document.getInitialProps(ctx);
return {
...initialProps,
styles: (
<>
{ initialProps.styles }
{ sheet.getStyleElement() }
</>
),
};
} finally {
sheet.seal();
}
}}
I've seen a lot of articles about how to do it with rendering regular JSX components, but i want to do it with the object notation.
Upvotes: 4
Views: 9149
Reputation: 1022
You can return a custom render()
from within that class which will allow you to decorate <html>
with the lang
attribute you want.
import Document, { Html, Head, Main, NextScript } from "next/document";
export default class CustomDocument extends Document {
static async getInitialProps(ctx) {
...
}
render() {
return (
<Html lang="en">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
This is your full code:
import Document, { Html, Head, Main, NextScript } from "next/document";
import { ServerStyleSheet } from "styled-components";
export default class CustomDocument extends Document {
static async getInitialProps(ctx) {
const sheet = new ServerStyleSheet();
const originalRenderPage = ctx.renderPage;
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: App => props => sheet.collectStyles(<App {...props} />),
});
const initialProps = await Document.getInitialProps(ctx);
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
),
};
} finally {
sheet.seal();
}
}
render() {
return (
<Html lang="en">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
More info here - Link to docs
All of
<Html />
,<Head />
,<Main />
and<NextScript />
are required for page to be properly rendered.
Upvotes: 6