Skip to content

Navigation

Bryce Russell edited this page Feb 11, 2023 · 7 revisions

Create a list of links using JavaScript objects, useful for configuration files and more

Features

  • Create a list of links using only props
  • Pass attributes if link is 'active'
  • Define default attributes applied to all links
  • Use slots functions to customize links
  • Define alternative render for active links

When do I use this?

This component is useful when using a config to control navigation on your website, though it has many helpful features that make it useful any time there is a list of links on your site

How to Use

---
import { Navigation } from 'astro-headless-ui';

const links = {
    active: { class: 'active' }, 
    defaults: { class: 'link' },
    links: [
        {
            text: 'Home',
            href: '/'
        },
        {
            text: 'Services',
            href: '/services'
        },
        {
            text: 'About Us',
            href: '/about-us'
        }
    ]
}
---

<nav>
  <Navigation {...links}/>
</nav>

Output:

<nav>
  <a class="link active" href="/">Home</a>
  <a class="link" href="/services">Services</a>
  <a class="link" href="/about-us">About Us</a>  
</nav>

Props

interface Link extends HTMLAttributes<'a'> {
    text?: string;
    active?: Link;
}

links: Link[]

An array of <Link> prop objects, each entry in this array creates a new link

defaults?: Link

A default <Link> prop object passed to all links

This prop helps you avoid repeating attributes for every link in links prop

active?: Link

A <Link> prop object passed to any link that is active (Astro.url.pathname === href)

Slot Arguments

All slots have access to a link argument for defining rendering templates

<Navigation {...links}>
  {({active, text, ...attrs}) => <li><a {...attrs}>{text}</a></li>}
</Navigation>

Slots

default

Default rendering template for all links

Example:

<Navigation {...links}>
  {({active, text, ...attrs}) => <li><a {...attrs}>{text}</a></li>}
</Navigation>

active

Rendering template for 'active' links only

Example:

<Navigation {...links}>
  <active slot="active">
    {({text, ...active}, text: _, ...attrs}) => <li><a {...attrs, ...active}>{text}</a></li>}
  </active>
</Navigation>

Examples

Customize Using Slots

<Navigation {...links}>
  {({active, text, ...attrs}) => <li><a {...attrs}>{text}</a></li>}
</Navigation>
<Navigation {...links}>
  <active slot="active">
    {({text, ...active}, text: _, ...attrs}) => <li><a {...attrs, ...active}>{text}</a></li>}
  </active>
</Navigation>
Clone this wiki locally