#Get previous and next page in collection

1 messages · Page 1 of 1 (latest)

bleak shadowBOT
#

Hi @weary lantern. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To get the next and previous page in the collection when you click on the link, you can use Astro's built-in pagination feature. This feature is supported via the paginate() function, which automatically generates an array to return from getStaticPaths(), creating one URL for every page of the paginated collection. The page number will be passed as a param, and the page data will be passed as a page prop.

Here's an example of how you can use the paginate() function:

export async function getStaticPaths({ paginate }) {
  // Load your data with fetch(), Astro.glob(), etc.
  const unitEntries = await getCollection('units');
  // Return a paginated collection of paths for all posts
  return paginate(unitEntries, { pageSize: 10 });
}

// If set up correctly, The page prop now has everything that
// you need to render a single page.
const { page } = Astro.props;

Source: Astro Documentation (https://docs.astro.build/en/reference/api-reference#paginate)

Once you have set up the paginate() function, each page will be passed its data via a page prop. The page prop has many useful properties, including page.url.next and page.url.prev, which are links to the next and previous page in the set, respectively.

Here's how you can use these properties:

const { page } = Astro.props;
---
<h1>Page {page.currentPage}</h1>
<ul>
 {page.data.map(({ unit }) => <li>{unit}</li>)}
</ul>
{page.url.prev ? <a href={page.url.prev}>Previous</a> : null}
{page.url.next ? <a href={page.url.next}>Next</a> : null}

Source: Astro Documentation (https://docs.astro.build/en/core-concepts/routing#the-page-prop)

#

This way, when you click on the "Next" or "Previous" link, you will be taken to the next or previous page in the collection, respectively.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: