Search code examples
sveltesapper

How to change route on button click in Sapper?


I know it's possible to go to a route using

<a href="/example"></a>

but was wondering if it was possible with a button component alone and not by wrapping an <a> tag around the button.

what I am looking for is something similar to this:

<button goto={"/example"}>Goto a page</button>

Solution

  • You can use goto for this...

    <script>
      import { goto } from '@sapper/app';
    </script>
    
    <button on:click={() => goto('/example')}>Goto a page</button>
    

    ...but you probably shouldn't. Links are links, buttons are buttons. If something causes navigation, you're much better off using an <a> — using a button is bad for accessibility, bad for SEO, and bad for usability (no middle-click to open in new tab, etc). It's bad all around unless you really know what you're doing!