NavBar Example

This is a responsive navigation bar component built with front.js.

Resize the window to see the mobile menu toggle in action.

How It Works

The NavBar component uses fine-grained reactivity to toggle the mobile menu. The state isOpen tracks whether the mobile menu is visible:

const isOpen = val(false);

When you click the hamburger button, isOpen toggles and the component automatically re-renders to show/hide the mobile menu.

Component Code

The NavBar component demonstrates several front.js patterns:

import { html } from 'uhtml';
import { val } from '../front.esm.js';

export function NavBar(props) {
  const isOpen = val(false);
  const links = props.links || [];

  return () => html`
    <nav class="navbar">
      <div class="navbar-container">
        <a href="/" class="navbar-brand">front.js</a>
        
        <!-- Mobile toggle button -->
        <button 
          class="navbar-toggle" 
          onclick=\${() => isOpen(!isOpen())}
        >
          <span class="hamburger"></span>
        </button>

        <!-- Desktop menu -->
        <div class="navbar-menu desktop">
          \${links.map(link => html`
            <a href="\${link.url}" class="navbar-link">
              \${link.label}
            </a>
          `)}
        </div>
      </div>

      <!-- Mobile menu (conditionally visible) -->
      <div class="\${`navbar-mobile-menu \${isOpen() ? 'open' : ''}`}">
        \${links.map(link => html`
          <a 
            href="\${link.url}" 
            class="navbar-link"
            onclick=\${() => setTimeout(() => isOpen(false), 50)}
          >
            \${link.label}
          </a>
        `)}
      </div>
    </nav>
  `;
}

Usage - Server (HTML)

Mark the island with the component name and pass navigation links as props:

<div
  data-island
  data-component="NavBar"
  data-props='{
    "links": [
      {"label": "Home", "url": "/"},
      {"label": "Examples", "url": "/examples/"},
      {"label": "Docs", "url": "/docs/"},
      {"label": "GitHub", "url": "https://github.com/watthem/front-js"}
    ]
  }'
></div>

Usage - Client (JavaScript)

Register the component and hydrate:

import { register, hydrate } from '../front.esm.js';
import { NavBar } from '../components/NavBar.js';

register('NavBar', NavBar);
hydrate();

📱 Mobile Layout (< 768px)

On mobile devices, the navigation links collapse into a hamburger menu. The mobile menu slides down when the hamburger button is clicked.

💻 Desktop Layout (≥ 768px)

On desktop, the navigation links are displayed horizontally in the navbar.

Key Patterns

← Back to Examples