How to use function instead of class in Nextjs custom document for Styled Components?

Viewed 4233

I'm using NextJS and Styled Components. Reading the documentation below I added a custom _document.js in NextJS to make Styled Components works.

Styled Components Doc

The example code is written in a React Class, is there a way of converting this to a function?

2 Answers

This is possible since Next 11.1.1, thanks to #28515, but the feature seems currently undocumented.
See an example below:

import { Html, Head, Main, NextScript } from 'next/document'

const Document = () => (
  <Html>
    <Head/>
    <body>
      <Main />
      <NextScript />
    </body>
  </Html>
)

export default Document

The answer is that there is no good way to do it, I guess you could somehow override it but Next.js uses _document and _app for in its custom runtime and it is not a good idea to override it.

_document's purpose:

A custom Document is commonly used to augment your application's <html> and <body> tags.

Also, note that using any logic (apart from this inside getInitialProps) inside _document is unadvisable: https://nextjs.org/docs/advanced-features/custom-document#caveats

Related