How to build Simple Page Application

Fasty come with RiotJS which allow you to create Web components easily. A Simple Page Application involve a router & components. Let see how to create a basic one.

First you need too be sure that you have everything ready in your layout. You should load Riot & the riot router JS files

{{ external | https://cdnjs.cloudflare.com/ajax/libs/riot/3.13.2/riot+compiler.min.js }}
{{ external | https://cdn.jsdelivr.net/npm/riot-route@3.1.2/dist/route.min.js }}

Then create a new Application and set fields. Choose a name (e.g demo) and set

HTML/JS

{{ riot | component1#component2#component3 }}

<div id="app"></div>

And define the router

document.addEventListener('DOMContentLoaded', function() {
  route('/', function(name) { riot.mount('div#app', 'component1') })
  route('/component-1', function(name) { riot.mount('div#app', 'component1') })
  route('/component-2', function(name) { riot.mount('div#app', 'component2') })
  route('/component-3', function(name) { riot.mount('div#app', 'component3') })
  route.start(true)
})

You can now create your RiotJS components.

component1

<component1>
  <h1>I am component 1</h1>
  <a href="#" onclick={gotoComponent2}>Component 2</a>
  <a href="#" onclick={gotoComponent3}>Component 3</a>
  
  
  <script>
    gotoComponent2(e) {
      e.preventDefault();
      route("/component2");
      return false;
    }
    
    gotoComponent3(e) {
      e.preventDefault();
      route("/component3");
      return false;
    }
  
    this.on("mount", function() {
      console.log("component1 is mounted");
    })
  </script>
</component1>

component2

<component2>
  <h1>I am component 2</h1>
  <a href="#" onclick={gotoComponent1}>Component 1</a>
  <a href="#" onclick={gotoComponent3}>Component 3</a>
  
  
  <script>
    gotoComponent1(e) {
      e.preventDefault();
      route("/component1");
      return false;
    }
    
    gotoComponent3(e) {
      e.preventDefault();
      route("/component3");
      return false;
    }
  
    this.on("mount", function() {
      console.log("component2 is mounted");
    })
  </script>
</component2>

And component3

<component3>
  <h1>I am component 3</h1>
  <a href="#" onclick={gotoComponent1}>Component 1</a>
  <a href="#" onclick={gotoComponent2}>Component 2</a>
  
  
  <script>
    gotoComponent1(e) {
      e.preventDefault();
      route("/component1");
      return false;
    }
    
    gotoComponent2(e) {
      e.preventDefault();
      route("/component2");
      return false;
    }
  
    this.on("mount", function() {
      console.log("component3 is mounted");
    })
  </script>
</component3>

Now you need to load your app by iniserting {{ spa | demo }} where you want. demo is you SPA's name

DEMO


Leave a comment