Building a Simple SPA with Riot.js
Why Choose Riot.js?
Riot.js is a lightweight, component-based UI library for developing web applications. Its simplicity, performance, and modularity make it an excellent choice for developers who want to build fast and efficient user interfaces.
Riot.js is designed to be easy to learn and use, making it perfect for developers who are familiar with HTML and JavaScript. Its small codebase and flexible architecture allow for seamless integration with other libraries and frameworks.
Key Features of Riot.js
- Declarative component syntax
- Powerful template system
- Inbuilt virtual DOM
- Support for custom tags and attributes
- Flexible and extensible API
- Strong community support
Riot.js vs. Web Components API
Riot.js and Web Components API share similar goals, but they approach the development of reusable and modular web components differently. While Web Components uses standardized APIs to construct unique elements and attach them to the DOM, Riot.js employs a template syntax and a limited set of directives to define components.
Building a Simple SPA with Riot.js
Setting Up the Project
To create a Riot.js project, navigate to a directory of your choice and run the following command:
npm install riot-cli -g
Create a new Riot.js project using the SPA template:
riot new my-app --template=webpack-spa
Creating the Quotes Page
Create a new file called quotes.riot
in the src/pages
directory:
<quotes> <h1>Quotes</h1> <ul> <li each={quote in quotes}>{quote.text}</li> </ul> </quotes>
Adding the Quotes Page Component
Register the quotes page component in the app.riot
file:
<app> <router> <route path="/quotes" component="quotes"></route> </router> </app>
Fetching the Quotes Data
Create a state object with a quotes property in the quotes.riot
file:
this.state = { quotes: [] }
Create an async function to fetch the quotes data:
async getQuotes() { const response = await fetch('undefineddummyjson.com/quotes') const data = await response.json() this.state.quotes = data.quotes }
Call the getQuotes
function in the onBeforeMount
lifecycle hook:
onBeforeMount() { this.getQuotes() }
Creating the Quotes Component
Create a new file called quote.riot
in the src/components
directory:
<quote> <p>{props.quote.text}</p> <p>— {props.quote.author}</p> </quote>
Register the quote component in the quotes.riot
file:
<quotes> <h1>Quotes</h1> <ul> <li each={quote in state.quotes}> <quote quote={quote}></quote> </li> </ul> </quotes>
Setting Up Dynamic Routing
Let’s set up dynamic routing to open a single quote on a new page when clicked.
Creating the Quote Page Route
Create a new file called quote-page.riot
in the src/pages
directory:
<quote-page> <h1>{props.quote.text}</h1> <p>— {props.quote.author}</p> </quote-page>
Register the quote page component in the app.riot
file:
<app> <router> <route path="/quotes/:id" component="quote-page"></route> </router> </app>