Menus

How to fetch and render menus.


There are two ways to fetch and render menus with next-drupal:

  1. `getMenu`: a helper to fetch menus in `getStaticProps` and `getServerSideProps`.
  2. `useMenu`: a client-side hook to fetch menus. Queries your Drupal site at runtime.

Use `useMenu` if you have menus that change frequently. Otherwise use `getMenu` which is faster (static) and does not need to query your Drupal site at runtime.

⚠️

You need to install the JSON:API Menu Items module to use `useMenu` and `getMenu`.

getMenu Example

pages/[...slug].tsx

import Link from "next/link"
import { getMenu } from "next-drupal"
// node and menu will be populated at build time by getStaticProps
export default function Page({ node, menu }) {
return (
<>
<ul>
{menu?.map((item) => {
return (
<li key={item.id}>
<Link href={item.url} passHref>
<a>{item.title}</a>
</Link>
</li>
)
})}
</ul>
<article>
<h1>{node.title}</h1>
// ...
</article>
</>
)
}
export async function getStaticPaths(context) {
return {
paths: await getPathsFromContext("node--page", context),
fallback: false,
}
}
export async function getStaticProps() {
const node = await getResourceFromContext("node--page", context)
// Fetch the main menu.
const { tree } = await getMenu("main")
return {
props: {
node,
menu: tree,
},
}
}

useMenu Example

pages/[...slug].tsx

import Link from "next/link"
import { useMenu } from "next-drupal"
export default function Page({ node }) {
const { tree } = useMenu("main")
return (
<>
<ul>
{tree?.map((item) => {
return (
<li key={item.id}>
<Link href={item.url} passHref>
<a>{item.title}</a>
</Link>
</li>
)
})}
</ul>
<article>
<h1>{node.title}</h1>
// ...
</article>
</>
)
}