Search code examples
javascriptreactjsnext.jsserver-side-renderingnext.js13

Include UI interactivity inside Server Component in NextJS


Considering the following Server Component inside the new app/ directory in NextJS:

export default async function RootLayout({ children }) {
  const categories = await getCategories();

  // const [navigation, setNavigation] = React.useState('hidden');

  function handleHover() {
     // hide or show the navigation bar without losing server side rendering
}

  return (
    <html lang="en">
      <body className={poppins.className}>
        <header className={"fixed left-0 top-0 w-full"}>
          <div
            className={
              "flex w-full flex-col items-center justify-center space-y-4 p-6 shadow"
            }
          >
            <div
              className={
                "flex flex-row items-center justify-center space-x-5 font-extralight"
              }
            >
              {categories.map((data) => (
                <Link onMouseEnter={handleHover} href={"/new"} className={"link uppercase"}>
                  {data}
                </Link>
              ))}
            </div>
          </div>
          <div
            className={`${navigation} nav-bar z-10 min-h-[250px] w-full justify-center p-6 shadow`}
          ></div>
        </header>

        <div className={"mx-auto 2xl:container"}>{children}</div>
      </body>
    </html>
  );
}

I need to show the nav-bar div when the mouse hovers over a category. This would work when using "use client", however I don't want to lose Server Side Rendering.

How can I do this?


Solution

  • You cannot do it. you need user interactivity and in server components, you cannot have user interactivity because you are on the server not on the browser environment.

    When you hover the mouse on the element, the mouseover event gets triggered by the browser and action gets executed by the javascript engine.

    server components are helpful for computation-heavy tasks because you can scale up your server to send the response quicker. Or they are helpful for SEO purposes. So if you render the navbar on client you are not going to lose too much.