Search code examples
javascriptreactjsnext.jssidebar

Adding a persistent component to _app.js in Nextjs


So I am playing around with my first Nextjs app and am having trouble with adding a persistent sidebar.

I found Adam Wathan's article on persistent layouts in nextjs, but it seems like there is a newer pattern that was added recently using the _app.js page. I went to the docs and a few of the github issues around it, but it doesn't looks like there's a lot of documentation around it yet.

So for my example, I have my _app.js file:

import '../css/tailwind.css'
import Head from 'next/head'
import Sidebar from "../components/Sidebar";

export default function App({Component, pageProps}){
  return(
    <>
      <Head />
        <Component {...pageProps} />
    </>
  )
}
import React, { useState } from "react";
import Transition from "../components/Transition";
import Link from 'next/link'

function Sidebar({ children }) {
 const [isSidebarOpen, setIsSidebarOpen] = useState(false);
  const [hideSidebarMenu, setHideSidebarMenu] = useState(true);

  const openSidebar = () => {
    setIsSidebarOpen(true);
    setHideSidebarMenu(false);
  };

  const closeSidebar = () => {
    setIsSidebarOpen(false);
  };

  const hideSidebar = () => {
    setHideSidebarMenu(true);
  };

  return(
    <div>
      /*sidebar links here*/
    </div>
  )
}

export default Sidebar;

How do I integrate my sidebar component into this? I've tried adding it next to component and wrapping component and a few other iterations with no luck. Hopefully I'm just missing something simple.


Solution

  • This is odd. I could have swore I tried this very simple solution before, but something like this was completely sufficient.

    This solution will feed in the page that you are on using the children prop in the sidebar.

    import '../css/tailwind.css'
    import Head from 'next/head'
    import Sidebar from "../components/Sidebar";
    
    export default function App({Component, pageProps}){
      return(
        <>
          <Head />
          <Sidebar >
            <Component {...pageProps} />
          </Sidebar>
        </>
      )
    }
    

    this option will just render the sidebar along with the content

    import '../css/tailwind.css'
    import Head from 'next/head'
    import Sidebar from "../components/Sidebar";
    
    export default function App({Component, pageProps}){
      return(
        <>
          <Head />
          <Sidebar />
          <Component {...pageProps} />
        </>
      )
    }