Adding Jump Links to Modules
- #Tips & Tricks
- #Modules
Want to add a link that takes a user to a specific module on a page?
... like this one (to the FAQs)
SanityPress comes included with a Studio component and a frontend helper function to make this possible—and it's quite easy.
The Studio Component🔗
The Accordion list module has the code already added:
sanity/schemas/modules/accordion-list.ts
export default defineType({
name: 'accordion-list',
...
fields: [
...
defineField({
name: 'uid',
title: 'Unique Identifier',
type: 'uid',
group: 'options',
}),
],
})
Which adds the following component:
Checkout the source code for this schema+input component; it's all in a single file for easy copy/paste.
The Frontend🔗
Then in your Next.js frontend component file, make the following additions to set the id attribute to then be able to use as jump links.
src/ui/modules/AccordionList.tsx
import moduleProps from '@/lib/moduleProps'
export default function AccordionList({
...props
}: Partial<{ ... }> & Sanity.Module) {
return (
<section
className="..."
{...moduleProps(props)}
>
...
</section>
)
}
This will add the following HTML attributes that you can use as reference for jump links or with CSS.
<section id="my-jump-link" data-module="accordion-list">
...
</section>
Say, you set the uid
value as my-jump-link
. Now, your module can be linked directly like this:
<a href="#my-jump-link">Jump link</a>
<!-- if linking to another page -->
<a href="/another-page#my-jump-link">Jump link</a>