Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Next.js how to add a class to body or _next div during SSR?

I have a use case where I have to add a class to a root element may it be body or _next during SSR. The class needs to be added conditionally/dynamically based on getInitialProps responses. I want to know if such is possible in the current state of Next.js.

like image 575
Jonathan Dsouza Avatar asked Feb 06 '20 06:02

Jonathan Dsouza


1 Answers

import React from "react";
import NextDocument, { Html, Head, Main, NextScript } from "next/document";

class Document extends NextDocument {
  static async getInitialProps(ctx) {
    const initialProps = await NextDocument.getInitialProps(ctx);

    // Determine if class name should be added
    return {
      ...initialProps,
      shouldShow: true,
    };
  }

  render() {
    return (
      <Html>
        <Head>
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          <style>
            {`#__next {
                height: ${this.props.shouldShow ? "100%" : "0"}
              }`}
          </style>
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default Document;
like image 55
leerob Avatar answered Oct 01 '22 15:10

leerob