Skip to content
Advertisement

How to add custom class to body element for some routes – nexjts

I want to add my custom class to some pages. for example

all pages must be this class fixed-header exception this routes:

JavaScript

this class add or remove to body element.

JavaScript

but I don’t know how I can handle this scenario?

Advertisement

Answer

Create a custom _document.js and _app.js in your pages directory.

A small util to check if class exists on body (to avoid duplicate class, thanks to suggestion by @juliomalves):

JavaScript

Server Side rendering

In _document.js, use the __NEXT_DATA__ prop to get access to the current page, check if the page is in your allowed routes, and add the classes to body.

JavaScript

The above code always runs on the server. Classes doesn’t get appended to the body on client-side navigation.

Client side rendering

To fix the above issue, use the same logic in _app.js in a useEffect, so that it adds the correct class when rendering on the client.

JavaScript

This solves the issue where client side navigation correctly applies the class on the allowed route. The code in _document.js makes sure that when a page is server rendered, it is sent downstream with the correct class applied so that it doesn’t cause a flash of incorrect styles on the client.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement