Search code examples
javascripthyperhtml

Navigation with links in hyperHTML and hyperhtml-app


I'm just starting out with hyperHTML. I'm building a little app which needs routing, so I've coupled it with hyperhtml-app.

I'm trying to set up the click handler on a view to handle clicks on anchor elements and have them navigate with the router. The following works, but it seems a convoluted and I think I'm missing a better way to do it. Can you suggest a better way?

import hyper from 'hyperhtml';
import hyperApp from 'hyperhtml-app';

const app = hyperApp();

class Welcome extends hyper.Component {
  render() {
    return this.html`
      <h1>Welcome</h1>
      <a href="/settings" onclick=${this}>settings</a>
    `;
  }

  onclick(e) {
    if (e.target instanceof HTMLAnchorElement) {
      e.preventDefault();
      app.navigate(e.target.attributes.href.value);
    }
  }
}

class Settings extends hyper.Component {
  render() {
    return this.html`<h1>Settings</h1>`;
  }
}

app.get('/', () => hyper(document.body)`${new Welcome()}`);

app.get('/settings', () => hyper(document.body)`${new Settings()}`);

app.navigate('/');

Solution

  • The purpose of they router is to handle the navigation for you.

    You actually need to preventDefault only when you don't want the router to work.

    I have created a Code Pen example that shows your exact same code without even bothering the click at all.

    As last note, if you want to keep the state of the previous pages you should probably address them once and just reuse them per each render.

    const page = {
      welcome: new Welcome,
      settings: new Settings
    };
    
    app.get('/', () => hyper(document.body)`${page.welcome}`);
    
    app.get('/settings', () => hyper(document.body)`${page.settings}`);
    

    If you have any other question please don't hesitate to ask.

    Regards