Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Manage a Navigation Menu in NextJS with WordPress

I'm building a NextJS app using headless WordPress with GraphQL. It's not clear from the documentation where I should be calling the query to create the site navigation. https://github.com/lfades/next.js/tree/examples/cms-wordpress/examples/cms-wordpress

The navigation is controlled dynamically by WordPress Menus (Appearance > Menus) on the backend and I can successfully access these menuItems via GraphQL without any issue on the index.js and posts/[slug].js page templates in Next JS.

// index.js
export default function Index({ primaryMenu = [] }) {
   return (
     <Layout>
         <Header> 
          {primaryMenu.map((item, index) => {
             return (<a href={item.url}>{item.label}</a>)
          )}
         </Header>
     </Layout>
   );

}

export async function getStaticProps() {
  const primaryMenu = await getPrimaryMenu(); // Get menu via GraphQL
  return {
    props: { primaryMenu },
  };
}

The issue I'm having with this is I am repeating the getStaticProps function on each template and I should be able to use some sort of global query for this, either in the <header/> component itself or another method. I'm unable to find documentation on how to do this and it doesn't work in components.

Any guidance (or examples) on where a global query such as a dynamic Navigation query would live in a NextJS app is appreciated.

like image 536
Darren Cooney Avatar asked Nov 16 '22 06:11

Darren Cooney


1 Answers

There are a couple of ways you can do it:

  1. You can menuItems query with useQuery() from @apollo/client inside the Layout component so that its available to all pages which are wrapped inside the Layout. However the problem with this is that, there will be a load time and the data won't be prefetched and readily available like we can do with getServerSideProps() ( at page level ). Because this will be at component level.

    import { useQuery } from "@apollo/client";

    export default function Layout () {

    const { loading, data } = useQuery( GET_MENU_QUERY ) return {...} }

  2. You can use swr that uses caching strategy. There is blog that explains how to use it

like image 57
Imran Sayed Avatar answered Jan 20 '23 01:01

Imran Sayed