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

孤者浪人 提交于 2021-01-28 01:31:57

问题


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.


回答1:


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;


来源:https://stackoverflow.com/questions/60088660/using-next-js-how-to-add-a-class-to-body-or-next-div-during-ssr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!