Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js custom class on body using _document.js

I'm using the example here

https://github.com/zeit/next.js#custom-document

and I want to change the custom_class on the body tag

I have tried passing props on calling components but nothing works. I want to add a 'dark' class based on some condition but I have no idea how to change this.

EDIT:

I'm not sure this is possible. After getting help from the nextjs slack channel I was told

"Pages get rendered client side with next/link
And body is not touched after server side rendering"

I'm going to try and wrap things in another tag that I generate and try and change that.

like image 585
32423hjh32423 Avatar asked Apr 02 '18 10:04

32423hjh32423


People also ask

How do I add a class to my body on NextJS?

If you want to add a class ( className ) to the body tag of a a NextJS page, you'll need to add it via JavaScript in the useEffect (or componentDidMount if you're using class-based components) Lifecycle function. This adds TailWindCSS's font-light and text-gray-700 classes to the body tag.

How do I use external CSS in next JavaScript?

You can add the css file in head of nextjs. and in the render method, inside the return add a head tag similar to ordinary HTML, the head tag should be inside a div. also the css should be in static folder. Add a key to the link tag to reuse the css in multiple pages.

How do I use getInitialProps in next JS?

Make sure the returned object from getInitialProps is a plain Object and not using Date , Map or Set . For the initial page load, getInitialProps will run on the server only. getInitialProps will then run on the client when navigating to a different route via the next/link component or by using next/router .

What is _APP js in NextJS?

Using _app. js will be rendered on every page. this is a good way to do custom layouts without having to wrap each page component in your /pages directory.


1 Answers

The cleanest solution I found is not declarative, but it works well:

import Head from "next/head"

class HeadElement extends React.Component {
    componentDidMount() {
        const {bodyClass} = this.props
        document.querySelector("body").classList.add(bodyClass || "light")
    }

    render() {
        return <Head>
            {/* Whatever other stuff you're using in Head */}
        </Head>
    }
}

export default HeadElement

With this Head component you would pass in "dark" or "light" (following the question's example for light/dark themes) as the bodyClass prop from the page.

like image 152
Jacquen Avatar answered Sep 21 '22 05:09

Jacquen