Views

How to fetch and render views.


You can use the `getView` helper to fetch and render views.

⚠️

You need to install the JSON:API Views module to use `getView`.

Example

Let's say you have a `field_view` on a `node`. The `field_view` returns a view value as follows: `NAME--DISPLAY`.

You can use `getView` in `getStaticProps` to load the view and pass the results to the component.

pages/[...slug].tsx

import Link from "next/link"
import { getView } from "next-drupal"
export default function Page({ node }) {
return (
<>
<article>
<h1>{node.title}</h1>
// ...
</article>
// highlight-start
<h2>Related Articles ({node.field_view?.meta?.count})</h2>
<ul>
{node.field_view?.results.map((article) => {
return (
<li key={item.id}>
<Link href={article.url} passHref>
<a>{properties.title}</a>
</Link>
</li>
)
})}
</ul>
// highlight-end
</h2>
)
}
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)
// Load the view and inline it to node.
if (node.field_view) {
node.field_view = await getView(node.field_view)
}
return {
props: {
node,
},
}
}

Reference

See the reference to learn more about using filters, JSON:API params and TypeScript with `getView`.