Next.js Discord

Discord Forum

Modifying body tag from further down component tree

Unanswered
Atlantic menhaden posted this in #help-forum
Open in Discord
Atlantic menhadenOP
how do i apply classes / attributes to the body / html further down in the component tree without using vanilla js to modify the dom since that's frowned upon (e.g. document.body)

6 Replies

Sun bear
what would you need this for
if you really need to do this you can create a ref for the body then pass it through context or as props
@Sun bear what would you need this for
Atlantic menhadenOP
the root layout is a server component. the main purpose for this is changing the direction of the page between rtl and ltr as well as changing themes and previewing themes
Sun bear
import { useRef } from "react"

export default function Layout() {
  const bodyRef = useRef(null)  

  return (
    <body ref={bodyRef}>
      {/* Rest of the code */}
    </body>
  )
}
if it's only for the themes take a look at next-themes package