Getting started with Svelte - Learn web development

Getting started with Svelte
===========================

* Previous
* Overview: Client-side JavaScript frameworks
* Next

In this article we'll provide a quick introduction to the Svelte framework. We will see how Svelte works and what sets it apart from the rest of the frameworks and tools we've seen so far. Then we will learn how to set up our development environment, create a sample app, understand the structure of the project, and see how to run it locally and build it for production.

|  |  |
| --- | --- |
| Prerequisites: |
 At minimum, it is recommended that you are familiar with the core
 HTML,
 CSS, and
 JavaScript languages, and
 have knowledge of the
 terminal/command line.

 Svelte is a compiler that generates minimal and highly optimized
 JavaScript code from our sources; you'll need a terminal with node +
 npm installed to compile and build your app.
  |
| Objective: |
 To setup a local Svelte development environment, create and build a
 starter app, and understand the basics of how it works.
  |

Svelte: A new approach to building rich user interfaces
-------------------------------------------------------

Svelte provides a different approach to building web apps than some of the other frameworks covered in this module. While frameworks like React and Vue do the bulk of their work in the user's browser while the app is running, Svelte shifts that work into a compile step that happens only when you build your app, producing highly optimized vanilla JavaScript.

The outcome of this approach is not only smaller application bundles and better performance, but also a developer experience that is more approachable for people that have limited experience of the modern tooling ecosystem.

Svelte sticks closely to the classic web development model of HTML, CSS, and JS, just adding a few extensions to HTML and JavaScript. It arguably has fewer concepts and tools to learn than some of the other framework options.

Its main current disadvantages are that it is a young framework — its ecosystem is therefore more limited in terms of tooling, support, plugins, clear usage patterns, etc. than more mature frameworks, and there are also fewer job opportunities. But its advantages should be enough to make you interested to explore it.

**Note:** Svelte has official TypeScript support. We'll look at it later on in this tutorial series.

We encourage you to go through the Svelte tutorial for a really quick introduction to the basic concepts, before returning to this tutorial series to learn how to build something slightly more in-depth.

Use cases
---------

Svelte can be used to develop small pieces of an interface or whole applications. You can either start from scratch letting Svelte drive your UI or you can incrementally integrate it into an existing application.

Nevertheless, Svelte is particularly appropriate to tackle the following situations:

* Web applications intended for low-power devices: Applications built with Svelte have smaller bundle sizes, which is ideal for devices with slow network connections and limited processing power. Less code means fewer KB to download, parse, execute, and keep hanging around in memory.
* Highly interactive pages or complex visualizations: If you are building data-visualizations that need to display a large number of DOM elements, the performance gains that come from a framework with no runtime overhead will ensure that user interactions are snappy and responsive.
* Onboarding people with basic web development knowledge: Svelte has a shallow learning curve. Web developers with basic HTML, CSS, and JavaScript knowledge can easily grasp Svelte specifics in a short time and start building web applications.

The Svelte team launched SvelteKit, a framework for building web applications using Svelte. It contains features found in modern web frameworks, such as filesystem-based routing, server-side rendering (SSR), page-specific rendering modes, offline support, and more. For more information about SvelteKit, see the official tutorial and documentation.

**Note:** SvelteKit is designed to replace Sapper as the recommended Svelte framework for building web applications.

Svelte is also available for mobile development via Svelte Native.

How does Svelte work?
---------------------

Being a compiler, Svelte can extend HTML, CSS, and JavaScript, generating optimal JavaScript code without any runtime overhead. To achieve this, Svelte extends vanilla web technologies in the following ways:

* It extends HTML by allowing JavaScript expressions in markup and providing directives to use conditions and loops, in a fashion similar to handlebars.
* It extends CSS by adding a scoping mechanism, allowing each component to define its own styles without the risk of clashing with other components' styles.
* It extends JavaScript by reinterpreting specific directives of the language to achieve true reactivity and ease component state management.

The compiler only intervenes in very specific situations and only in the context of Svelte components. Extensions to the JavaScript language are minimal and carefully picked in order not to break JavaScript syntax or alienate developers. In fact, you will be mostly working with vanilla JavaScript.

First steps with Svelte
-----------------------

Since Svelte is a compiler, you can't just add a `<script src="svelte.js">` tag to your page and import it into your app. You'll have to set up your development environment in order to let the compiler do its job.

### Requirements

In order to work with Svelte, you need to have Node.js installed. It's recommended that you use the long-term support (LTS) version. Node includes npm (the node package manager), and npx (the node package runner). Note that you can also use the Yarn package manager in place of npm, but we'll assume you are using npm in this set of tutorials. See Package management basics for more information on npm and yarn.

If you're using Windows, you will need to install some software to give you parity with Unix/macOS terminal in order to use the terminal commands mentioned in this tutorial. Gitbash (which comes as part of the git for Windows toolset) or Windows Subsystem for Linux (WSL) are both suitable. See Command line crash course for more information on these, and on terminal commands in general.

Also see the following for more information:

* "About npm" on the npm documentation
* "Introducing npx" on the npm blog
### Creating your first Svelte app

The easiest way to create a starter app template is to just download the starter template application. You can do that by visiting sveltejs/template on GitHub, or you can avoid having to download and unzip it and just use degit.

To create your starter app template, run the following terminal commands:

```bash
npx degit sveltejs/template moz-todo-svelte
cd moz-todo-svelte
npm install
npm run dev
```

**Note:** degit doesn't do any kind of magic — it just lets you download and unzip the latest version of a git repo's contents. This is much quicker than using `git clone` because it will not download all the history of the repo, or create a complete local clone.

After running `npm run dev`, Svelte will compile and build your application. It will start a local server at `localhost:8080`. Svelte will watch for file updates, and automatically recompile and refresh the app for you when changes are made to the source files. Your browser will display something like this:

![A simple start page that says hello world, and gives a link to the official svelte tutorials](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_getting_started/01-svelte-starter-app.png)

### Application structure

The starter template comes with the following structure:
```

moz-todo-svelte
├── README.md
├── package.json
├── package-lock.json
├── rollup.config.js
├── .gitignore
├── node_modules
├── public
│   ├── favicon.png
│   ├── index.html
│   ├── global.css
│   └── build
│       ├── bundle.css
│       ├── bundle.js
│       └── bundle.js.map
├── scripts
│   └── setupTypeScript.js
└── src
    ├── App.svelte
    └── main.js
```

The contents are as follows:

* `package.json` and `package-lock.json`: Contains information about the project that Node.js/npm uses to keep it organized. You don't need to understand this file at all to complete this tutorial, however, if you'd like to learn more, you can read about `package.json` handling on npmjs.com; we also talk about it in our Package management basics tutorial.
* `node_modules`: This is where node saves the project dependencies. These dependencies won't be sent to production, they are just used for development purposes.
* `.gitignore`: Tells git which files or folder to ignore from the project — useful if you decide to include your app in a git repo.
* `rollup.config.js`: Svelte uses rollup.js as a module bundler. This configuration file tells rollup how to compile and build your app. If you prefer webpack, you can create your starter project with `npx degit sveltejs/template-webpack svelte-app` instead.
* `scripts`: Contains setup scripts as required. Currently should only contain `setupTypeScript.js`.
    + `setupTypeScript.js`: This script sets up TypeScript support in Svelte. We'll talk about this more in the last article.
* `src`: This directory is where the source code for your application lives — where you'll be creating the code for your app.
    + `App.svelte`: This is the top-level component of your app. So far it just renders the 'Hello World!' message.
    + `main.js`: The entry point to our application. It just instantiates the `App` component and binds it to the body of our HTML page.
* `public`: This directory contains all the files that will be published in production.
    + `favicon.png`: This is the favicon for your app. Currently, it's the Svelte logo.
    + `index.html`: This is the main page of your app. Initially it's just an empty HTML page that loads the CSS files and js bundles generated by Svelte.
    + `global.css`: This file contains unscoped styles. It's a regular CSS file that will be applied to the whole application.
    + `build`: This folder contains the generated CSS and JavaScript source code.
        - `bundle.css`: The CSS file that Svelte generated from the styles defined for each component.
        - `bundle.js`: The JavaScript file compiled from all your JavaScript source code.
Having a look at our first Svelte component
-------------------------------------------

Components are the building blocks of Svelte applications. They are written into `.svelte` files using a superset of HTML.

All three sections — `<script>`, `<style>`, and markup — are optional, and can appear in any order you like.

```html
<script>
 // logic goes here
</script>

<style>
 /\* styles go here \*/
</style>

<!-- markup (zero or more HTML elements) goes here -->
```

**Note:** For more information on the component format, have a look at the Svelte Components documentation.

With this in mind, let's have a look at the `src/App.svelte` file that came with the starter template. You should see something like the following:

```html
<script>
 export let name;
</script>

<main>
  <h1>Hello {name}!</h1>
  <p>
    Visit the <a href="https://learn.svelte.dev/">Svelte tutorial</a> to learn
    how to build Svelte apps.
  </p>
</main>

<style>
 main {
 text-align: center;
 padding: 1em;
 max-width: 240px;
 margin: 0 auto;
 }

 h1 {
 color: #ff3e00;
 text-transform: uppercase;
 font-size: 4em;
 font-weight: 100;
 }

 @media (min-width: 640px) {
 main {
 max-width: none;
 }
 }
</style>
```

### The `<script>` section

The `<script>` block contains JavaScript that runs when a component instance is created. Variables declared (or imported) at the top level are 'visible' from the component's markup. Top-level variables are the way Svelte handles the component state, and they are reactive by default. We will explain in detail what this means later on.

```html
<script>
 export let name;
</script>
```

Svelte uses the `export` keyword to mark a variable declaration as a property (or prop), which means it becomes accessible to consumers of the component (e.g. other components). This is one example of Svelte extending JavaScript syntax to make it more useful, while keeping it familiar.

### The markup section

In the markup section you can insert any HTML you like, and in addition you can insert valid JavaScript expressions inside single curly braces (`{}`). In this case we are embedding the value of the `name` prop right after the `Hello` text.

```html
<main>
  <h1>Hello {name}!</h1>
  <p>
    Visit the <a href="https://learn.svelte.dev/">Svelte tutorial</a> to learn
    how to build Svelte apps.
  </p>
</main>
```

Svelte also supports tags like `{#if}`, `{#each}`, and `{#await}` — these examples allow you to conditionally render a portion of the markup, iterate through a list of elements, and work with async values, respectively.

### The `<style>` section

If you have experience working with CSS, the following snippet should make sense:

```html
<style>
 main {
 text-align: center;
 padding: 1em;
 max-width: 240px;
 margin: 0 auto;
 }

 h1 {
 color: #ff3e00;
 text-transform: uppercase;
 font-size: 4em;
 font-weight: 100;
 }

 @media (min-width: 640px) {
 main {
 max-width: none;
 }
 }
</style>
```

We are applying a style to our `<h1>` element. What will happen to other components with `<h1>` elements in them?

In Svelte, CSS inside a component's `<style>` block will be scoped only to that component. This works by adding a class to selected elements, which is based on a hash of the component styles.

You can see this in action by opening `localhost:8080` in a new browser tab, right/`Ctrl`-clicking on the *HELLO WORLD!* label, and choosing *Inspect*:

![Svelte starter app with devtools open, showing classes for scoped styles](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_getting_started/02-svelte-component-scoped-styles.png)

When compiling the app, Svelte changes our `h1` styles definition to `h1.svelte-1tky8bj`, and then modifies every `<h1>` element in our component to `<h1 class="svelte-1tky8bj">`, so that it picks up the styles as required.

**Note:** You can override this behavior and apply styles to a selector globally using the `:global()` modifier (see the Svelte `<style>` docs for more information).

Making a couple of changes
--------------------------

 Now that we have a general idea of how it all fits together, we can start making a few changes.
 At this point you can try updating your `App.svelte` component — for example change the `<h1>` element on line 6 of `App.svelte` so that it reads like this:

```html
<h1>Hello {name} from MDN!</h1>
```

Just save your changes and the app running at `localhost:8080` will be automatically updated.

### A first look at Svelte reactivity

In the context of a UI framework, reactivity means that the framework can automatically update the DOM when the state of any component is changed.

In Svelte, reactivity is triggered by assigning a new value to any top-level variable in a component. For example, we could include a `toggleName()` function in our `App` component, and a button to run it.

Try updating your `<script>` and markup sections like so:

```html
<script>
 export let name;

 function toggleName() {
 if (name === "world") {
 name = "Svelte";
 } else {
 name = "world";
 }
 }
</script>

<main>
  <h1>Hello {name}!</h1>
  <button on:click="{toggleName}">Toggle name</button>
  <p>
    Visit the <a href="https://learn.svelte.dev/">Svelte tutorial</a> to learn
    how to build Svelte apps.
  </p>
</main>
```

Whenever the button is clicked, Svelte executes the `toggleName()` function, which in turn updates the value of the `name` variable.

As you can see, the `<h1>` label is automatically updated. Behind the scenes, Svelte created the JavaScript code to update the DOM whenever the value of the name variable changes, without using any virtual DOM or other complex reconciliation mechanism.

Note the use of `:` in `on:click`. That's Svelte's syntax for listening to DOM events.

Inspecting main.js: the entry point of our app
----------------------------------------------

Let's open `src/main.js`, which is where the `App` component is being imported and used. This file is the entry point for our app, and it initially looks like this:

```js
import App from "./App.svelte";

const app = new App({
  target: document.body,
  props: {
    name: "world",
  },
});

export default app;
```

`main.js` starts by importing the Svelte component that we are going to use. Then in line 3 it instantiates it, passing an option object with the following properties:

* `target`: The DOM element inside which we want the component to be rendered, in this case the `<body>` element.
* `props`: the values to assign to each prop of the `App` component.
A look under the hood
---------------------

How does Svelte manage to make all these files work together nicely?

The Svelte compiler processes the `<style>` section of every component and compiles them into the `public/build/bundle.css` file.

It also compiles the markup and `<script>` section of every component and stores the result in `public/build/bundle.js`. It also adds the code in `src/main.js` to reference the features of each component.

Finally the file `public/index.html` includes the generated `bundle.css` and `bundle.js` files:

```html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />

    <title>Svelte app</title>

    <link rel="icon" type="image/png" href="/favicon.png" />
    <link rel="stylesheet" href="/global.css" />
    <link rel="stylesheet" href="/build/bundle.css" />

    <script defer src="/build/bundle.js"></script>
  </head>

  <body></body>
</html>
```

The minified version of `bundle.js` weighs a little more than 3KB, which includes the "Svelte runtime" (just 300 lines of JavaScript code) and the `App.svelte` compiled component. As you can see, `bundle.js` is the only JavaScript file referenced by `index.html`. There are no other libraries loaded into the web page.

This is a much smaller footprint than compiled bundles from other frameworks. Take into account that, in the case of code bundles, it's not just the size of the files you have to download that matter. This is executable code that needs to be parsed, executed, and kept in memory. So this really makes a difference, especially in low-powered devices or CPU-intensive applications.

Following this tutorial
-----------------------

In this tutorial series you will be building a complete web application. We'll learn all the basics about Svelte and also quite a few advanced topics.

You can just read the content to get a good understanding of Svelte features, but you'll get the most out of this tutorial if you follow along coding the app with us as you go. To make it easier for you to follow each article, we provide a GitHub repository with a folder containing the source for the app as it is at the start of each tutorial.

Svelte also provides an online REPL, which is a playground for live-coding Svelte apps on the web without having to install anything on your machine. We provide a REPL for each article so you can start coding along right away. Let's talk a bit more about how to use these tools.

### Using Git

The most popular version control system is Git, along with GitHub, a site that provides hosting for your repositories and several tools for working with them.

We'll be using GitHub so that you can easily download the source code for each article. You will also be able to get the code as it should be after completing the article, just in case you get lost.

After installing git, to clone the repository you should execute:

```bash
git clone https://github.com/opensas/mdn-svelte-tutorial.git
```

Then at the beginning of each article, you can just `cd` into the corresponding folder and start the app in dev mode to see what its current state should be, like this:

```bash
cd 02-starting-our-todo-app
npm install
npm run dev
```

If you want lo learn more about git and GitHub, we've compiled a list of links to useful guides — see Git and GitHub.

**Note:** If you just want to download the files without cloning the git repo, you can use the degit tool like this — `npx degit opensas/mdn-svelte-tutorial`. You can also download a specific folder with `npx degit opensas/mdn-svelte-tutorial/01-getting-started`. Degit won't create a local git repo, it will just download the files of the specified folder.

### Using the Svelte REPL

A REPL (read–eval–print loop) is an interactive environment that allows you to enter commands and immediately see the results — many programming languages provide a REPL.

Svelte's REPL is much more than that. It's an online tool that allows you to create complete apps, save them online, and share with others.

It's the easiest way to start playing with Svelte from any machine, without having to install anything. It is also widely used by Svelte community. If you want to share an idea, ask for help, or report an issue, it's always extremely useful to create a REPL instance demonstrating the issue.

Let's have a quick look at the Svelte REPL and how you'd use it. It looks like so:

![the svelte REPL in action, showing component code on the left, and output on the right](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_getting_started/03-svelte-repl-in-action.png)

To start a REPL, open your browser and navigate to https://svelte.dev/repl.

* On the left side of the screen you'll see the code of your components, and on the right you'll see the running output of your app.
* The bar above the code lets you create `.svelte` and `.js` files and rearrange them. To create a file inside a folder, just specify the complete pathname, like this: `components/MyComponent.svelte`. The folder will be automatically created.
* Above that bar you have the title of the REPL. Click on it to edit it.
* On the right side you have three tabs:
    + The *Result* tab shows your app output, and provides a console at the bottom.
    + The *JS output* tab lets you inspect the JavaScript code generated by Svelte and set compiler options.
    + The *CSS output* tab shows the CSS generated by Svelte.
* Above the tabs, you'll find a toolbar that lets you enter fullscreen mode and download your app. If you log in with a GitHub account, you'll also be able to fork and save the app. You'll also be able to see all your saved REPLs by clicking on your GitHub username profile and selecting *Your saved apps*.

Whenever you change any file on the REPL, Svelte will recompile the app and update the Result tab. To share your app, share the URL. For example, here's the link for a REPL running our complete app: https://svelte.dev/repl/378dd79e0dfe4486a8f10823f3813190?version=3.23.2.

**Note:** Notice how you can specify Svelte's version in the URL. This is useful when reporting issues related to a specific version of Svelte.

We will provide a REPL at the beginning and end of each article so that you can start coding with us right away.

**Note:** At the moment the REPL can't handle folder names properly. If you are following the tutorial on the REPL, just create all your components inside the root folder. Then when you see a path in the code, for example `import Todos from './components/Todos.svelte'`, just replace it with a flat URL, e.g. `import Todos from './Todos.svelte'`.

The code so far
---------------

### Git

Clone the GitHub repo (if you haven't already done it) with:

```bash
git clone https://github.com/opensas/mdn-svelte-tutorial.git
```

Then to get to the current app state, run

```bash
cd mdn-svelte-tutorial/01-getting-started
```

Or directly download the folder's content:

```bash
npx degit opensas/mdn-svelte-tutorial/01-getting-started
```

Remember to run `npm install && npm run dev` to start your app in development mode.

### REPL

To code along with us using the REPL, start at

https://svelte.dev/repl/fc68b4f059d34b9c84fa042d1cce586c?version=3.23.2

Summary
-------

This brings us to the end of our initial look at Svelte, including how to install it locally, create a starter app, and how the basics work. In the next article we'll start building our first proper application, a todo list. Before we do that, however, let's recap some of the things we've learned.

In Svelte:

* We define the script, style, and markup of each component in a single `.svelte` file.
* Component props are declared with the `export` keyword.
* Svelte components can be used just by importing the corresponding `.svelte` file.
* Components styles are scoped, keeping them from clashing with each other.
* In the markup section you can include any JavaScript expression by putting it between curly braces.
* The top-level variables of a component constitute its state.
* Reactivity is fired just by assigning a new value to a top-level variable.
* Previous
* Overview: Client-side JavaScript frameworks
* Next


Routing in Ember - Learn web development

Routing in Ember
================

* Previous
* Overview: Client-side JavaScript frameworks
* Next

In this article we learn about **routing**, or URL-based filtering as it is sometimes referred to. We'll use it to provide a unique URL for each of the three todo views — "All", "Active", and "Completed".

|  |  |
| --- | --- |
| Prerequisites: |
 At minimum, it is recommended that you are familiar with the core
 HTML,
 CSS, and
 JavaScript languages, and
 have knowledge of the
 terminal/command line.

 A deeper understanding of modern JavaScript features (such as classes,
 modules, etc.), will be extremely beneficial, as Ember makes heavy use
 of them.
  |
| Objective: | To learn about implementing routing in Ember. |

URL-based filtering
-------------------

Ember comes with a routing system that has a tight integration with the browser URL. Typically, when writing web applications, you want the page to be represented by the URL so that if (for any reason), the page needs to refresh, the user isn't surprised by the state of the web app — they can link directly to significant views of the app.

At the moment, we already have the "All" page, as we are currently not doing any filtering in the page that we've been working with, but we will need to reorganize it a bit to handle a different view for the "Active" and "Completed" todos.

An Ember application has a default "application" route, which is tied to the `app/templates/application.hbs` template. Because that application template is the entry point to our todo app, we'll need to make some changes to allow for routing.

Creating the routes
-------------------

Let's start by creating three new routes: "Index", "Active" and "Completed". To do this you'll need to enter the following commands into your terminal, inside the root directory of your app:

```bash
ember generate route index
ember generate route completed
ember generate route active
```

The second and third commands should have not only generated new files, but also updated an existing file, `app/router.js`. It contains the following contents:

```js
import EmberRouter from "@ember/routing/router";
import config from "./config/environment";

export default class Router extends EmberRouter {
  location = config.locationType;
  rootURL = config.rootURL;
}

Router.map(function () {
  this.route("completed");
  this.route("active");
});
```

The highlighted lines were added when the 2nd and 3rd commands above were run.

`router.js` behaves as a "sitemap" for developers to be able to quickly see how the entire app is structured. It also tells Ember how to interact with your route, such as when loading arbitrary data, handling errors while loading that data, or interpreting dynamic segments of the URL. Since our data is static, we won't get to any of those fancy features, but we'll still make sure that the route provides the minimally required data to view a page.

Creating the "Index" route did not add a route definition line to `router.js`, because like with URL navigation and JavaScript module loading, "Index" is a special word that indicates the default route to render, load, etc.

To adjust our old way of rendering the TodoList app, we'll first need to replace the TodoList component invocation from the application template with an `{{outlet}}` call, which means "any sub-route will be rendered in place here".

Go to the `todomvc/app/templates/application.hbs` file and replace

```hbs
<TodoList />
```

With

```hbs
{{outlet}}
```

Next, in our `index.hbs`, `completed.hbs`, and `active.hbs` templates (also found in the templates directory) we can for now just enter the TodoList component invocation.

In each case, replace

```hbs
{{outlet}}
```

with

```hbs
<TodoList />
```

So at this point, if you try the app again and visit any of the three routes

`localhost:4200 localhost:4200/active localhost:4200/completed`

you'll see exactly the same thing. At each URL, the template that corresponds to the specific path ("Active", "Completed", or "Index"), will render the `<TodoList />` component. The location in the page where `<TodoList />` is rendered is determined by the `{{ outlet }}` inside the parent route, which in this case is `application.hbs`. So we have our routes in place. Great!

But now we need a way to differentiate between each of these routes, so that they show what they are supposed to show.

First of all, return once more to our `todo-data.js` file. It already contains a getter that returns all todos, and a getter that returns incomplete todos. The getter we are missing is one to return just the completed todos. Add the following below the existing getters:

```js
get completed() {
  return this.todos.filter((todo) => todo.isCompleted);
}
```

Models
------

Now we need to add models to our route JavaScript files to allow us to easily return specific data sets to display in those models. `model` is a data loading lifecycle hook. For TodoMVC, the capabilities of model aren't that important to us; you can find more information in the Ember model guide if you want to dig deeper. We also provide access to the service, like we did for the components.

### The index route model

First of all, update `todomvc/app/routes/index.js` so it looks as follows:

```js
import Route from "@ember/routing/route";
import { inject as service } from "@ember/service";

export default class IndexRoute extends Route {
  @service("todo-data") todos;

  model() {
    let todos = this.todos;

    return {
      get allTodos() {
        return todos.all;
      },
    };
  }
}
```

We can now update the `todomvc/app/templates/index.hbs` file so that when it includes the `<TodoList />` component, it does so explicitly with the available model, calling its `allTodos()` getter to make sure all of the todos are shown.

In this file, change

```hbs
<TodoList />
```

To

```hbs
<TodoList @todos={{ @model.allTodos }} />
```

### The completed route model

Now update `todomvc/app/routes/completed.js` so it looks as follows:

```js
import Route from "@ember/routing/route";
import { inject as service } from "@ember/service";

export default class CompletedRoute extends Route {
  @service("todo-data") todos;

  model() {
    let todos = this.todos;

    return {
      get completedTodos() {
        return todos.completed;
      },
    };
  }
}
```

We can now update the `todomvc/app/templates/completed.hbs` file so that when it includes the `<TodoList />` component, it does so explicitly with the available model, calling its `completedTodos()` getter to make sure only the completed todos are shown.

In this file, change

```hbs
<TodoList />
```

To

```hbs
<TodoList @todos={{ @model.completedTodos }} />
```

### The active route model

Finally for the routes, let's sort out our active route. Start by updating `todomvc/app/routes/active.js` so it looks as follows:

```js
import Route from "@ember/routing/route";
import { inject as service } from "@ember/service";

export default class ActiveRoute extends Route {
  @service("todo-data") todos;

  model() {
    let todos = this.todos;

    return {
      get activeTodos() {
        return todos.incomplete;
      },
    };
  }
}
```

We can now update the `todomvc/app/templates/active.hbs` file so that when it includes the `<TodoList />` component, it does so explicitly with the available model, calling its `activeTodos()` getter to make sure only the active (incomplete) todos are shown.

In this file, change

```hbs
<TodoList />
```

To

```hbs
<TodoList @todos={{ @model.activeTodos }} />
```

Note that, in each of the route model hooks, we are returning an object with a getter instead of a static object, or more just the static list of todos (for example, `this.todos.completed`). The reason for this is that we want the template to have a dynamic reference to the todo list, and if we returned the list directly, the data would never re-compute, which would result in the navigations appearing to fail / not actually filter. By having a getter defined in the return object from the model data, the todos are re-looked-up so that our changes to the todo list are represented in the rendered list.

Getting the footer links working
--------------------------------

So our route functionality is now all in place, but we can't access them from our app. Let's get the footer links active so that clicking on them goes to the desired routes.

Go back to `todomvc/app/components/footer.hbs`, and find the following bit of markup:

```hbs
<a href="#">All</a>
<a href="#">Active</a>
<a href="#">Completed</a>
```

Update it to

```hbs
<LinkTo @route="index">All</LinkTo>
<LinkTo @route="active">Active</LinkTo>
<LinkTo @route="completed">Completed</LinkTo>
```

`<LinkTo>` is a built-in Ember component that handles all the state changes when navigating routes, as well as setting an "active" class on any link that matches the URL, in case there is a desire to style it differently from inactive links.

Updating the todos display inside TodoList
------------------------------------------

One small final thing that we need to fix is that previously, inside `todomvc/app/components/todo-list.hbs`, we were accessing the todo-data service directly and looping over all todos, as shown here:

```hbs
{{#each this.todos.all as |todo| }}
```

Since we now want to have our TodoList component show a filtered list, we'll want to pass an argument to the TodoList component representing the "current list of todos", as shown here:

```hbs
{{#each @todos as |todo| }}
```

And that's it for this tutorial! Your app should now have fully working links in the footer that display the "Index"/default, "Active", and "Completed" routes.

![The todo list app, showing the routing working for all, active, and completed todos.](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_routing/todos-navigation.gif)

Summary
-------

Congratulations! You've finished this tutorial!

There is a lot more to be implemented before what we've covered here has parity with the original TodoMVC app, such as editing, deleting, and persisting todos across page reloads.

To see our finished Ember implementation, checkout the finished app folder in the repository for the code of this tutorial or see the live deployed version here. Study the code to learn more about Ember, and also check out the next article, which provides links to more resources and some troubleshooting advice.

* Previous
* Overview: Client-side JavaScript frameworks
* Next


Getting started with Ember - Learn web development

Getting started with Ember
==========================

* Previous
* Overview: Client-side JavaScript frameworks
* Next

In our first Ember article we will look at how Ember works and what it's useful for, install the Ember toolchain locally, create a sample app, and then do some initial setup to get it ready for development.

|  |  |
| --- | --- |
| Prerequisites: |
 At minimum, it is recommended that you are familiar with the core
 HTML,
 CSS, and
 JavaScript languages, and
 have knowledge of the
 terminal/command line.

 A deeper understanding of modern JavaScript features (such as classes,
 modules, etc.), will be extremely beneficial, as Ember makes heavy use
 of them.
  |
| Objective: | To learn how to install Ember, and create a starter app. |

Introducing Ember
-----------------

Ember is a component-service framework that focuses on the overall web application development experience, minimizing the trivial differences between applications — all while being a modern and light layer on top of native JavaScript. Ember also has immense backwards and forwards compatibility to help businesses stay up to date with the latest versions of Ember and latest community-driven conventions.

What does it mean to be a component-service framework? Components are individual bundles of behavior, style, and markup — much like what other frontend frameworks provide, such as React, Vue, and Angular. The service side provides long-lived shared state, behavior, and an interface to integrating with other libraries or systems. For example, the Router (which will be mentioned later in this tutorial) is a service. Components and Services make up the majority of any EmberJS application.

Use cases
---------

Generally, EmberJS works well for building apps that desire either or both of the following traits:

* Single Page Applications, including native-like web apps, and progressive web apps (PWAs)
    + Ember works best when it is the entire front end of your application.
* Increasing cohesion among many team's technology stacks
    + Community-backed "best practices" allow for faster long-term development speed.
    + Ember has clear conventions that are useful for enforcing consistency and helping team members get up to speed quickly.
### Ember with add-ons

EmberJS has a plugin architecture, which means that add-ons can be installed and provide additional functionality without much, if any, configuration.

Examples include:

* PREmber: Static website rendering for blogs or marketing content.
* FastBoot: Server-side rendering, including improving search-engine optimization (SEO), or improving initial render performance of complex, highly interactive web pages.
* empress-blog: Authoring blog posts in markdown while optimizing for SEO with PREmber.
* ember-service-worker: Configuring a PWA so that the app can be installed on mobile devices, just like apps from the device's respective app-store.
### Native mobile apps

Ember can also be used with native mobile apps with a native-mobile bridge to JavaScript, such as that provided by Corber.

Opinions
--------

EmberJS is one of the most opinionated front-end frameworks out there. But what does it mean to be opinionated? In Ember, opinions are a set of conventions that help increase the efficiency of developers at the cost of having to learn those conventions. As conventions are defined and shared, the opinions that back those conventions help reduce the menial differences between apps — a common goal among all opinionated frameworks, across any language and ecosystem. Developers are then more easily able to switch between projects and applications without having to completely relearn the architecture, patterns, conventions, etc.

As you work through this series of tutorials, you'll notice Ember's opinions — such as strict naming conventions of component files.

How does Ember relate to vanilla JavaScript?
--------------------------------------------

Ember is built on JavaScript technologies and is a thin layer on top of traditional object-oriented programming, while still allowing developers to utilize functional programming techniques.

Ember makes use of two main syntaxes:

* JavaScript (or optionally, TypeScript)
* Ember's own templating language, which is loosely based on Handlebars.

The templating language is used to make build and runtime optimizations that otherwise wouldn't be possible. Most importantly, it is a superset of HTML — meaning that anyone who knows HTML can make meaningful contributions to any Ember project with minimal fear of breaking code. Designers and other non-developers can contribute to page templates without any knowledge of JavaScript, and interactivity can be added later.

This language also enables lighter asset payloads due to *compiling* the templates into a "byte code" that can be parsed faster than JavaScript. The **Glimmer VM** enables extremely fast DOM change tracking without the need to manage and diff a cached virtual representation (which is a common approach to mitigating the slow I/O of DOM changes).

For more information on the technical aspects of The Glimmer VM, the GitHub repository has some documentation — specifically, References and Validators may be of interest.

Everything else in Ember is *just* JavaScript. In particular, JavaScript classes. This is where most of the "framework" parts come into play, as there are superclasses, where each type of *thing* has a different purpose and different expected location within your project.

 Here is a demonstration the impact Ember has on the JavaScript that is in typical projects:
 Gavin Demonstrates how < 20% of the JS written is specific to Ember.

![a set of code files with the ember-specific JavaScript highlighted, showing that only 20% of the Ember code is Ember-specific](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_getting_started/20percent-js-specific-ember.png)

Getting started
---------------

The rest of the Ember material you'll find here consists of a multi-part tutorial, in which we'll make a version of the classic TodoMVC sample app, teaching you how to use the essentials of the Ember framework along the way. TodoMVC is a basic to-do tracking app implemented in many different technologies.

Here is the completed Ember version, for reference.

### A note on TodoMVC and accessibility

The TodoMVC project has a few issues in terms of adhering to accessible/default web practices. There are a couple of GitHub issues open about this on the TodoMVC family of projects:

* Add keyboard access to demos
* Re-enable Outline on focusable elements

Ember has a strong commitment to being accessible by default and there is an entire section of the Ember Guides on accessibility on what it means for website / app design.

That said, because this tutorial is a focus on the JavaScript side of making a small web application, TodoMVC's value comes from providing pre-made CSS and recommended HTML structure, which eliminates small differences between implementations, allowing for easier comparison. Later on in the tutorial, we'll focus on adding code to our application to fix some of TodoMVC's biggest faults.

Installing the Ember tooling
----------------------------

Ember uses a command-line interface (CLI) tool for building and scaffolding parts of your application.

1. You'll need node and npm installed before you can install ember-cli. Go here to find out how to install node and npm, if you haven't already got them.
2. Now type the following into your terminal to install ember-cli:

```bash
npm install -g ember-cli
```

This tool provides the `ember` program in your terminal, which is used to create, build, develop, test, and scaffold your application (run `ember --help` for a full list of commands and their options).
3. To create a brand new application, type the following in your terminal. This creates a new directory inside the current directory you are in called todomvc, containing the scaffolding for a new Ember app. Make sure you navigate to somewhere appropriate in the terminal before you run it. (Good suggestions are your "desktop" or "documents" directories, so that it is easy to find):

```bash
ember new todomvc
```

Or, on Windows:

```bash
npx ember-cli new todomvc
```

This generates a production-ready application development environment that includes the following features by default:

* Development server with live reload.
* Plugin-architecture that allows for third-party packages to richly enhance your application.
* The latest JavaScript via Babel and Webpack integration.
* Automated testing environment that runs your tests in the browser, allowing you to *test like a user*.
* Transpilation, and minification, of both CSS and JavaScript for production builds.
* Conventions for minimizing the differences between applications (allowing easier mental context switching).
Getting ready to build our Ember project
----------------------------------------

You'll need a code editor before continuing to interact with your brand new project. If you don't have one configured already, The Ember Atlas has some guides on how to set up various editors.

### Installing the shared assets for TodoMVC projects

Installing shared assets, as we're about to do, isn't normally a required step for new projects, but it allows us to use existing shared CSS so we don't need to try to guess at what CSS is needed to create the TodoMVC styles.

1. First, enter into your `todomvc` directory in the terminal, for example using `cd todomvc` in macOS/Linux.
2. Now run the following command to place the common todomvc CSS inside your app:

```bash
npm install --save-dev todomvc-app-css todomvc-common
```

3. Next, find the ember-cli-build.js file inside the todomvc directory (it's right there inside the root) and open it in your chosen code editor. ember-cli-build.js is responsible for configuring details about how your project is built — including bundling all your files together, asset minification, and creating sourcemaps — with reasonable defaults, so you don't typically need to worry about this file.
 We will however add lines to the ember-cli-build.js file to import our shared CSS files, so that they become part of our build without having to explicitly `@import` them into the `app.css` file (this would require URL rewrites at build time and therefore be less efficient and more complicated to set up).
4. In `ember-cli-build.js`, find the following code:

```js
let app = new EmberApp(defaults, {
  // Add options here
});
```

5. Add the following lines underneath it before saving the file:

```js
app.import("node\_modules/todomvc-common/base.css");
app.import("node\_modules/todomvc-app-css/index.css");
```

For more information on what `ember-cli-build.js` does, and for other ways in which you can customize your build / pipeline, the Ember Guides have a page on Addons and Dependencies.
6. Finally, find `app.css`, located at `app/styles/app.css`, and paste in the following:

```css
:focus,
.view label:focus,
.todo-list li .toggle:focus + label,
.toggle-all:focus + label {
  /\* !important needed because todomvc styles deliberately disable the outline \*/
  outline: #d86f95 solid !important;
}
```

This CSS overrides some of the styles provided by the `todomvc-app-css` npm package, therefore allowing keyboard focus to be visible. This goes some way towards fixing one of the major accessibility disadvantages of the default TodoMVC app.

### Starting the development server

You may start the app in *development* mode by typing the following command in your terminal, while inside the `todomvc` directory:

```bash
ember server
```

This should give you an output similar to the following:
```

Build successful (190ms) – Serving on http://localhost:4200/

Slowest Nodes (totalTime >= 5%)          | Total (avg)
-----------------------------------------+-----------
BroccoliMergeTrees (17)                  | 35ms (2 ms)
Package /assets/vendor.js (1)            | 13ms
Concat: Vendor Styles/assets/vend... (1) | 12ms
```

The development server launches at `http://localhost:4200`, which you can visit in your browser to check out what your work looks like so far.

If everything is working correctly, you should see a page like this:

![The default start page when you create a new Ember app, with a cartoon mascot, saying congratulations](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_getting_started/ember-start-page.png)

**Note:** on Windows systems without Windows Subsystem for Linux (WSL), you will experience slower build-times overall compared to macOS, Linux, and Windows *with* WSL.

Summary
-------

So far so good. We've got to the point where we can start build up our sample TodoMVC app in Ember. In the next article we'll look at building up the markup structure of our app, as a group of logical components.

* Previous
* Overview: Client-side JavaScript frameworks
* Next


Dynamic behavior in Svelte: working with variables and props - Learn web development

Dynamic behavior in Svelte: working with variables and props
============================================================

* Previous
* Overview: Client-side JavaScript frameworks
* Next

Now that we have our markup and styles ready, we can start developing the required features for our Svelte to-do list app. In this article we'll be using variables and props to make our app dynamic, allowing us to add and delete to-dos, mark them as complete, and filter them by status.

|  |  |
| --- | --- |
| Prerequisites: |
 At minimum, it is recommended that you are familiar with the core
 HTML,
 CSS, and
 JavaScript languages, and
 have knowledge of the
 terminal/command line.

 You'll need a terminal with node and npm installed to compile and build
 your app.
  |
| Objective: |
 Learn and put into practice some basic Svelte concepts, like creating
 components, passing data using props, rendering JavaScript expressions into
 our markup, modifying the components' state, and iterating over lists.
  |

Code along with us
------------------

### Git

Clone the GitHub repo (if you haven't already done it) with:

```bash
git clone https://github.com/opensas/mdn-svelte-tutorial.git
```

Then to get to the current app state, run

```bash
cd mdn-svelte-tutorial/03-adding-dynamic-behavior
```

Or directly download the folder's content:

```bash
npx degit opensas/mdn-svelte-tutorial/03-adding-dynamic-behavior
```

Remember to run `npm install && npm run dev` to start your app in development mode.

### REPL

To code along with us using the REPL, start at

https://svelte.dev/repl/c862d964d48d473ca63ab91709a0a5a0?version=3.23.2

Working with to-dos
-------------------

Our `Todos.svelte` component is currently just displaying static markup; let's start making it a bit more dynamic. We'll take the tasks information from the markup and store it in a `todos` array. We'll also create two variables to keep track of the total number of tasks and the completed tasks.

The state of our component will be represented by these three top-level variables.

1. Create a `<script>` section at the top of `src/components/Todos.svelte` and give it some content, as follows:

```svelte
<script>
 let todos = [
 { id: 1, name: "Create a Svelte starter app", completed: true },
 { id: 2, name: "Create your first component", completed: true },
 { id: 3, name: "Complete the rest of the tutorial", completed: false }
 ];
 let totalTodos = todos.length;
 let completedTodos = todos.filter((todo) => todo.completed).length;
</script>
```

Now let's do something with that information.
2. Let's start by showing a status message. Find the `<h2>` heading with an `id` of `list-heading` and replace the hardcoded number of active and completed tasks with dynamic expressions:

```svelte
<h2 id="list-heading">{completedTodos} out of {totalTodos} items completed</h2>
```

3. Go to the app, and you should see the "2 out of 3 items completed" message as before, but this time the information is coming from the `todos` array.
4. To prove it, go to that array, and try changing some of the to-do object's completed property values, and even add a new to-do object. Observe how the numbers in the message are updated appropriately.
Dynamically generating the to-dos from the data
-----------------------------------------------

At the moment, our displayed to-do items are all static. We want to iterate over each item in our `todos` array and render the markup for each task, so let's do that now.

HTML doesn't have a way of expressing logic — like conditionals and loops. Svelte does. In this case we use the `{#each}` directive to iterate over the `todos` array. The second parameter, if provided, will contain the index of the current item. Also, a key expression can be provided, which will uniquely identify each item. Svelte will use it to diff the list when data changes, rather than adding or removing items at the end, and it's a good practice to always specify one. Finally, an `:else` block can be provided, which will be rendered when the list is empty.

Let's give it a try.

1. Replace the existing `<ul>` element with the following simplified version to get an idea of how it works:

```svelte
<ul>
{#each todos as todo, index (todo.id)}
  <li>
    <input type="checkbox" checked={todo.completed}/> {index}. {todo.name} (id: {todo.id})
  </li>
{:else}
  Nothing to do here!
{/each}
</ul>
```

2. Go back to the app; you'll see something like this:

 ![very simple to-do list output created using an each block](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_variables_props/01-each-block.png)
3. Now that we've seen that this is working, let's generate a complete to-do item with each loop of the `{#each}` directive, and inside embed the information from the `todos` array: `id`, `name`, and `completed`. Replace your existing `<ul>` block with the following:

```svelte
<!-- To-dos -->
<ul role="list" class="todo-list stack-large" aria-labelledby="list-heading">
  {#each todos as todo (todo.id)}
  <li class="todo">
    <div class="stack-small">
      <div class="c-cb">
        <input
 type="checkbox"
 id="todo-{todo.id}"
 checked={todo.completed} />
        <label for="todo-{todo.id}" class="todo-label"> {todo.name} </label>
      </div>
      <div class="btn-group">
        <button type="button" class="btn">
          Edit <span class="visually-hidden">{todo.name}</span>
        </button>
        <button type="button" class="btn btn\_\_danger">
          Delete <span class="visually-hidden">{todo.name}</span>
        </button>
      </div>
    </div>
  </li>
  {:else}
  <li>Nothing to do here!</li>
  {/each}
</ul>
```

Notice how we are using curly braces to embed JavaScript expressions in HTML attributes, like we did with the `checked` and `id` attributes of the checkbox.

We've turned our static markup into a dynamic template ready to display the tasks from our component's state. Great! We are getting there.

Working with props
------------------

With a hardcoded list of to-dos, our `Todos` component is not very useful. To turn our component into a general purpose to-do editor, we should allow the parent of this component to pass in the list of to-dos to edit. This would allow us to save them to a web service or local storage and later retrieve them for update. So let's turn the array into a `prop`.

1. In `Todos.svelte`, replace the existing `let todos = …` block with `export let todos = []`.

```js
export let todos = [];
```

This may feel a little weird at first. That's not how `export` normally works in JavaScript modules! This is how Svelte 'extends' JavaScript by taking valid syntax and giving it a new purpose. In this case Svelte is using the `export` keyword to mark a variable declaration as a property or prop, which means it becomes accessible to consumers of the component.
 You can also specify a default initial value for a prop. This will be used if the component's consumer doesn't specify the prop on the component — or if its initial value is undefined — when instantiating the component.
 So with `export let todos = []`, we are telling Svelte that our `Todos.svelte` component will accept a `todos` attribute, which when omitted will be initialized to an empty array.
2. Have a look at the app, and you'll see the "Nothing to do here!" message. This is because we are currently not passing any value into it from `App.svelte`, so it's using the default value.
3. Now let's move our to-dos to `App.svelte` and pass them to the `Todos.svelte` component as a prop. Update `src/App.svelte` as follows:

```svelte
<script>
 import Todos from "./components/Todos.svelte";

 let todos = [
 { id: 1, name: "Create a Svelte starter app", completed: true },
 { id: 2, name: "Create your first component", completed: true },
 { id: 3, name: "Complete the rest of the tutorial", completed: false }
 ];
</script>

<Todos todos={todos} />
```

4. When the attribute and the variable have the same name, Svelte allows you to just specify the variable as a handy shortcut, so we can rewrite our last line like this. Try this now.

```svelte
<Todos {todos} />
```

At this point your to-dos should render just like they did before, except that now we're passing them in from the `App.svelte` component.

Toggling and removing to-dos
----------------------------

Let's add some functionality to toggle the task status. Svelte has the `on:eventname` directive for listening to DOM events. Let's add a handler to the `on:click` event of the checkbox input to toggle the completed value.

1. Update the `<input type="checkbox">` element inside `src/components/Todos.svelte` as follows:

```svelte
<input type="checkbox" id="todo-{todo.id}"
 on:click={() => todo.completed = !todo.completed}
 checked={todo.completed}
/>
```

2. Next we'll add a function to remove a to-do from our `todos` array. At the bottom of the `<script>` section of `Todos.svelte`, add the `removeTodo()` function like so:

```js
function removeTodo(todo) {
  todos = todos.filter((t) => t.id !== todo.id);
}
```

3. We'll call it via the *Delete* button. Update it with a `click` event, like so:

```svelte
<button type="button" class="btn btn\_\_danger"
 on:click={() => removeTodo(todo)}
>
  Delete <span class="visually-hidden">{todo.name}</span>
</button>
```

A very common mistake with handlers in Svelte is to pass the result of executing a function as a handler, instead of passing the function. For example, if you specify `on:click={removeTodo(todo)}`, it will execute `removeTodo(todo)` and the result will be passed as a handler, which is not what we had in mind.
 In this case you have to specify `on:click={() => removeTodo(todo)}` as the handler. If `removeTodo()` received no params, you could use `on:event={removeTodo}`, but not `on:event={removeTodo()}`. This is not some special Svelte syntax — here we are just using regular JavaScript arrow functions.

Again, this is good progress — at this point, we can now delete tasks. When a to-do item's *Delete* button is pressed, the relevant to-do is removed from the `todos` array, and the UI updates to no longer show it. In addition, we can now check the checkboxes, and the completed status of the relevant to-dos will now update in the `todos` array.

However, the "x out of y items completed" heading is not being updated. Read on to find out why this is happening and how we can solve it.

Reactive to-dos
---------------

As we've already seen, every time the value of a component top-level variable is modified, Svelte knows how to update the UI. In our app, the `todos` array value is updated directly every time a to-do is toggled or deleted, and so Svelte will update the DOM automatically.

The same is not true for `totalTodos` and `completedTodos`, however. In the following code they are assigned a value when the component is instantiated and the script is executed, but after that, their values are not modified:

```js
let totalTodos = todos.length;
let completedTodos = todos.filter((todo) => todo.completed).length;
```

We could recalculate them after toggling and removing to-dos, but there's an easier way to do it.

We can tell Svelte that we want our `totalTodos` and `completedTodos` variables to be reactive by prefixing them with `$:`. Svelte will generate the code to automatically update them whenever data they depend on is changed.

**Note:** Svelte uses the `$:` JavaScript label statement syntax to mark reactive statements. Just like the `export` keyword being used to declare props, this may look a little alien. This is another example in which Svelte takes advantage of valid JavaScript syntax and gives it a new purpose — in this case to mean "re-run this code whenever any of the referenced values change". Once you get used to it, there's no going back.

Update your `totalTodos` and `completedTodos` variable definitions inside `src/components/Todos.svelte` to look like so:

```js
$: totalTodos = todos.length;
$: completedTodos = todos.filter((todo) => todo.completed).length;
```

If you check your app now, you'll see that the heading's numbers are updated when to-dos are completed or deleted. Nice!

Behind the scenes the Svelte compiler will parse and analyze our code to make a dependency tree, and then it will generate the JavaScript code to re-evaluate each reactive statement whenever one of their dependencies is updated. Reactivity in Svelte is implemented in a very lightweight and performant way, without using listeners, setters, getters, or any other complex mechanism.

Adding new to-dos
-----------------

Now on to the next major task for this article — let's add some functionality for adding new to-dos.

1. First we'll create a variable to hold the text of the new to-do. Add this declaration to the `<script>` section of `Todos.svelte` file:

```js
let newTodoName = "";
```

2. Now we will use this value in the `<input>` for adding new tasks. To do that we need to bind our `newTodoName` variable to the `todo-0` input, so that the `newTodoName` variable value stays in sync with the input's `value` property. We could do something like this:

```svelte
<input value={newTodoName} on:keydown={(e) => newTodoName = e.target.value} />
```

Whenever the value of the variable `newTodoName` changes, it will be reflected in the `value` attribute of the input, and whenever a key is pressed in the input, we will update the contents of the variable `newTodoName`.
 This is a manual implementation of two-way data binding for an input box. But we don't need to do this — Svelte provides an easier way to bind any property to a variable, using the `bind:property` directive:

```svelte
<input bind:value={newTodoName} />
```

So, let's implement this. Update the `todo-0` input like so:

```svelte
<input
 bind:value={newTodoName}
 type="text"
 id="todo-0"
 autocomplete="off"
 class="input input\_\_lg" />
```

3. An easy way to test that this works is to add a reactive statement to log the contents of `newTodoName`. Add this snippet at the end of the `<script>` section:

```js
$: console.log("newTodoName: ", newTodoName);
```

**Note:** As you may have noticed, reactive statements aren't limited to variable declarations. You can put *any* JavaScript statement after the `$:` sign.
4. Now try going back to `localhost:5042`, pressing `Ctrl` + `Shift` + `K` to open your browser console and typing something into the input field. You should see your entries logged. At this point, you can delete the reactive `console.log()` if you wish.
5. Next up we'll create a function to add the new to-do — `addTodo()` — which will push a new `todo` object onto the `todos` array. Add this to the bottom of your `<script>` block inside `src/components/Todos.svelte`:

```js
function addTodo() {
  todos.push({ id: 999, name: newTodoName, completed: false });
  newTodoName = "";
}
```

**Note:** For the moment we are just assigning the same `id` to every to-do, but don't worry, we will fix that soon.
6. Now we want to update our HTML so that we call `addTodo()` whenever the form is submitted. Update the NewTodo form's opening tag like so:

```svelte
<form on:submit|preventDefault={addTodo}>
```

The `on:eventname` directive supports adding modifiers to the DOM event with the `|` character. In this case, the `preventDefault` modifier tells Svelte to generate the code to call `event.preventDefault()` before running the handler. Explore the previous link to see what other modifiers are available.
7. If you try adding new to-dos at this point, the new to-dos are added to the to-dos array, but our UI is not updated. Remember that in Svelte reactivity is triggered with assignments. That means that the `addTodo()` function is executed, the element is added to the `todos` array, but Svelte won't detect that the push method modified the array, so it won't refresh the tasks `<ul>`.
 Just adding `todos = todos` to the end of the `addTodo()` function would solve the problem, but it seems strange to have to include that at the end of the function. Instead, we'll take out the `push()` method and use spread syntax to achieve the same result: we'll assign a value to the `todos` array equal to the `todos` array plus the new object.

**Note:** `Array` has several mutable operations: `push()`, `pop()`, `splice()`, `shift()`, `unshift()`, `reverse()`, and `sort()`. Using them often causes side effects and bugs that are hard to track. By using the spread syntax instead of `push()` we avoid mutating the array, which is considered a good practice.

Update your `addTodo()` function like so:

```js
function addTodo() {
  todos = [...todos, { id: 999, name: newTodoName, completed: false }];
  newTodoName = "";
}
```

Giving each to-do a unique ID
-----------------------------

If you try to add new to-dos in your app now, you'll be able to add a new to-do and have it appear in the UI — once. If you try it a second time, it won't work, and you'll get a console message saying "Error: Cannot have duplicate keys in a keyed each". We need unique IDs for our to-dos.

1. Let's declare a `newTodoId` variable calculated from the number of to-dos plus 1, and make it reactive. Add the following snippet to the `<script>` section:

```js
let newTodoId;
$: {
  if (totalTodos === 0) {
    newTodoId = 1;
  } else {
    newTodoId = Math.max(...todos.map((t) => t.id)) + 1;
  }
}
```

**Note:** As you can see, reactive statements are not limited to one-liners. The following would work too, but it is a little less readable: `$: newTodoId = totalTodos ? Math.max(...todos.map((t) => t.id)) + 1 : 1`
2. How does Svelte achieve this? The compiler parses the whole reactive statement, and detects that it depends on the `totalTodos` variable and the `todos` array. So whenever either of them is modified, this code is re-evaluated, updating `newTodoId` accordingly.
 Let's use this in our `addTodo()` function. Update it like so:

```js
function addTodo() {
  todos = [...todos, { id: newTodoId, name: newTodoName, completed: false }];
  newTodoName = "";
}
```

Filtering to-dos by status
--------------------------

Finally for this article, let's implement the ability to filter our to-dos by status. We'll create a variable to hold the current filter, and a helper function that will return the filtered to-dos.

1. At the bottom of our `<script>` section add the following:

```js
let filter = "all";
const filterTodos = (filter, todos) =>
  filter === "active"
    ? todos.filter((t) => !t.completed)
    : filter === "completed"
      ? todos.filter((t) => t.completed)
      : todos;
```

We use the `filter` variable to control the active filter: *all*, *active*, or *completed*. Just assigning one of these values to the filter variable will activate the filter and update the list of to-dos. Let's see how to achieve this.
 The `filterTodos()` function will receive the current filter and the list of to-dos, and return a new array of to-dos filtered accordingly.
2. Let's update the filter button markup to make it dynamic and update the current filter when the user presses one of the filter buttons. Update it like this:

```svelte
<div class="filters btn-group stack-exception">
  <button class="btn toggle-btn" class:btn\_\_primary={filter === 'all'} aria-pressed={filter === 'all'} on:click={() => filter = 'all'} >
    <span class="visually-hidden">Show</span>
    <span>All</span>
    <span class="visually-hidden">tasks</span>
  </button>
  <button class="btn toggle-btn" class:btn\_\_primary={filter === 'active'} aria-pressed={filter === 'active'} on:click={() => filter = 'active'} >
    <span class="visually-hidden">Show</span>
    <span>Active</span>
    <span class="visually-hidden">tasks</span>
  </button>
  <button class="btn toggle-btn" class:btn\_\_primary={filter === 'completed'} aria-pressed={filter === 'completed'} on:click={() => filter = 'completed'} >
    <span class="visually-hidden">Show</span>
    <span>Completed</span>
    <span class="visually-hidden">tasks</span>
  </button>
</div>
```

There are a couple of things going on in this markup.
 We will show the current filter by applying the `btn__primary` class to the active filter button. To conditionally apply style classes to an element we use the `class:name={value}` directive. If the value expression evaluates to truthy, the class name will be applied. You can add many of these directives, with different conditions, to the same element. So when we issue `class:btn__primary={filter === 'all'}`, Svelte will apply the `btn__primary` class if filter equals all.

**Note:** Svelte provides a shortcut which allows us to shorten `<div class:active={active}>` to `<div class:active>` when the class matches the variable name.

Something similar happens with `aria-pressed={filter === 'all'}`: when the JavaScript expression passed between curly braces evaluates to a truthy value, the `aria-pressed` attribute will be added to the button.
 Whenever we click on a button, we update the filter variable by issuing `on:click={() => filter = 'all'}`. Read on to find out how Svelte reactivity will take care of the rest.
3. Now we just need to use the helper function in the `{#each}` loop; update it like this:

```svelte
…
  <ul role="list" class="todo-list stack-large" aria-labelledby="list-heading">
  {#each filterTodos(filter, todos) as todo (todo.id)}
…
```

After analyzing our code, Svelte detects that our `filterTodos()` function depends on the variables `filter` and `todos`. And, just like with any other dynamic expression embedded in the markup, whenever any of these dependencies changes, the DOM will be updated accordingly. So whenever `filter` or `todos` changes, the `filterTodos()` function will be re-evaluated and the items inside the loop will be updated.

**Note:** Reactivity can be tricky sometimes. Svelte recognizes `filter` as a dependency because we are referencing it in the `filterTodos(filter, todo)` expression. `filter` is a top-level variable, so we might be tempted to remove it from the helper function params, and just call it like this: `filterTodos(todo)`. This would work, but now Svelte has no way to find out that `{#each filterTodos(todos) }` depends on `filter`, and the list of filtered to-dos won't be updated when the filter changes. Always remember that Svelte analyzes our code to find out dependencies, so it's better to be explicit about it and not rely on the visibility of top-level variables. Besides, it's a good practice to make our code clear and explicit about what information it is using.

The code so far
---------------

### Git

To see the state of the code as it should be at the end of this article, access your copy of our repo like this:

```bash
cd mdn-svelte-tutorial/04-componentizing-our-app
```

Or directly download the folder's content:

```bash
npx degit opensas/mdn-svelte-tutorial/04-componentizing-our-app
```

Remember to run `npm install && npm run dev` to start your app in development mode.

### REPL

To see the current state of the code in a REPL, visit:

https://svelte.dev/repl/99b9eb228b404a2f8c8959b22c0a40d3?version=3.23.2

Summary
-------

That will do for now! In this article we already implemented most of our desired functionality. Our app can display, add, and delete to-dos, toggle their completed status, show how many of them are completed, and apply filters.

To recap, we covered the following topics:

* Creating and using components
* Turning static markup into a live template
* Embedding JavaScript expressions in our markup
* Iterating over lists using the `{#each}` directive
* Passing information between components with props
* Listening to DOM events
* Declaring reactive statements
* Basic debugging with `console.log()` and reactive statements
* Binding HTML properties with the `bind:property` directive
* Triggering reactivity with assignments
* Using reactive expressions to filter data
* Explicitly defining our reactive dependencies

In the next article we will add further functionality, which will allow users to edit to-dos.

* Previous
* Overview: Client-side JavaScript frameworks
* Next


Rendering a list of Vue components - Learn web development

Rendering a list of Vue components
==================================

* Previous
* Overview: Client-side JavaScript frameworks
* Next

At this point we've got a fully working component; we're now ready to add multiple `ToDoItem` components to our app. In this article we'll look at adding a set of todo item data to our `App.vue` component, which we'll then loop through and display inside `ToDoItem` components using the `v-for` directive.

|  |  |
| --- | --- |
| Prerequisites: |
 Familiarity with the core HTML,
 CSS, and
 JavaScript languages,
 knowledge of the
 terminal/command line.

 Vue components are written as a combination of JavaScript objects that
 manage the app's data and an HTML-based template syntax that maps to
 the underlying DOM structure. For installation, and to use some of the
 more advanced features of Vue (like Single File Components or render
 functions), you'll need a terminal with node + npm installed.
  |
| Objective: |
 To learn how to loop through an array of data and render it in multiple
 components.
  |

Rendering lists with v-for
--------------------------

To be an effective to-do list, we need to be able to render multiple to-do items. To do that, Vue has a special directive, `v-for`. This is a built-in Vue directive that lets us include a loop inside of our template, repeating the rendering of a template feature for each item in an array. We'll use this to iterate through an array of to-do items and display them in our app in separate `ToDoItem` components.

### Adding some data to render

First we need to get an array of to-do items. To do that, we'll add a `data` property to the `App.vue` component object, containing a `ToDoItems` field whose value is an array of todo items. While we'll eventually add a mechanism to add new todo items, we can start with some mock to do items. Each to-do item will be represented by an object with a `label` and a `done` property.

Add a few sample to-do items, along the lines of those seen below. This way you have some data available for rendering using `v-for`.

```js
export default {
  name: "app",
  components: {
    ToDoItem,
  },
  data() {
    return {
      ToDoItems: [
        { label: "Learn Vue", done: false },
        { label: "Create a Vue project with the CLI", done: true },
        { label: "Have fun", done: true },
        { label: "Create a to-do list", done: false },
      ],
    };
  },
};
```

Now that we have a list of items, we can use the `v-for` directive to display them. Directives are applied to elements like other attributes. In case of `v-for`, you use a special syntax similar to a `for...in` loop in JavaScript — `v-for="item in items"` — where `items` is the array you want to iterate over, and `item` is a reference to the current element in the array.

`v-for` attaches to the element you want to repeat, and renders that element and its children. In this case, we want to display an `<li>` element for every to-do item inside our `ToDoItems` array. Then we want to pass the data from each to-do item to a `ToDoItem` component.

### Key attribute

Before we do that, there's one other piece of syntax to know about that is used with `v-for`, the `key` attribute. To help Vue optimize rendering the elements in the list, it tries to patch list elements so it's not recreating them every time the list changes. However, Vue needs help. To make sure it is re-using list elements appropriately, it needs a unique "key" on the same element that you attach `v-for` to.

To make sure that Vue can accurately compare the `key` attributes, they need to be string or numeric values. While it would be great to use the name field, this field will eventually be controlled by user input, which means we can't guarantee that the names would be unique. We could use `lodash.uniqueid()`, however, like we did in the previous article.

1. Import `lodash.uniqueid` into your `App` component in the same way you did with your `ToDoItem` component, using

```js
import uniqueId from "lodash.uniqueid";
```

2. Next, add an `id` field to each element in your `ToDoItems` array, and assign each of them a value of `uniqueId('todo-')`.
 The `<script>` element in `App.vue` should now have the following contents:

```js
import ToDoItem from "./components/ToDoItem.vue";
import uniqueId from "lodash.uniqueid";

export default {
  name: "app",
  components: {
    ToDoItem,
  },
  data() {
    return {
      ToDoItems: [
        { id: uniqueId("todo-"), label: "Learn Vue", done: false },
        {
          id: uniqueId("todo-"),
          label: "Create a Vue project with the CLI",
          done: true,
        },
        { id: uniqueId("todo-"), label: "Have fun", done: true },
        { id: uniqueId("todo-"), label: "Create a to-do list", done: false },
      ],
    };
  },
};
```

3. Now, add the `v-for` directive and `key` attribute to the `<li>` element in your `App.vue` template, like so:

```html
<ul>
  <li v-for="item in ToDoItems" :key="item.id">
    <to-do-item label="My ToDo Item" :done="true"></to-do-item>
  </li>
</ul>
```

When you make this change, every JavaScript expression between the `<li>` tags will have access to the `item` value in addition to the other component attributes. This means we can pass the fields of our item objects to our `ToDoItem` component — just remember to use the `v-bind` syntax. This is really useful, as we want our todo items to display their `label` properties as their label, not a static label of "My Todo Item". In addition, we want their checked status to reflect their `done` properties, not always be set to `done="true"`.
4. Update the `label="My ToDo Item"` attribute to `:label="item.label"`, and the `:done="true"` attribute to `:done="item.done"`, as seen in context below:

```html
<ul>
  <li v-for="item in ToDoItems" :key="item.id">
    <to-do-item :label="item.label" :done="item.done"></to-do-item>
  </li>
</ul>
```

Now when you look at your running app, it'll show the todo items with their proper names, and if you inspect the source code you'll see that the inputs all have unique `id`s, taken from the object in the `App` component.

![The app with a list of todo items rendered.](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_rendering_lists/rendered-todo-items.png)

Chance for a slight refactor
----------------------------

There's one little bit of refactoring we can do here. Instead of generating the `id` for the checkboxes inside your `ToDoItem` component, we can turn the `id` into a prop. While this isn't strictly necessary, it makes it easier for us to manage since we already need to create a unique `id` for each todo item anyway.

1. Add a new prop to your `ToDoItem` component — `id`.
2. Make it required, and make its type a `String`.
3. To prevent name collisions, remove the `id` field from your `data` attribute.
4. You are no longer using `uniqueId`, so you need to remove the `import uniqueId from 'lodash.uniqueid';` line, otherwise your app will throw an error.

The `<script>` contents in your `ToDoItem` component should now look something like this:

```js
export default {
  props: {
    label: { required: true, type: String },
    done: { default: false, type: Boolean },
    id: { required: true, type: String },
  },
  data() {
    return {
      isDone: this.done,
    };
  },
};
```

Now, over in your `App.vue` component, pass `item.id` as a prop to the `ToDoItem` component. Your `App.vue` template should now look like this:

```html
<template>
  <div id="app">
    <h1>My To-Do List</h1>
    <ul>
      <li v-for="item in ToDoItems" :key="item.id">
        <to-do-item
 :label="item.label"
 :done="item.done"
 :id="item.id"></to-do-item>
      </li>
    </ul>
  </div>
</template>
```

When you look at your rendered site, it should look the same, but our refactor now means that our `id` is being taken from the data inside `App.vue` and passed into `ToDoItem` as a prop, just like everything else, so things are now more logical and consistent.

Summary
-------

And that brings us to the end of another article. We now have sample data in place, and a loop that takes each bit of data and renders it inside a `ToDoItem` in our app.

What we really need next is the ability to allow our users to enter their own todo items into the app, and for that we'll need a text `<input>`, an event to fire when the data is submitted, a method to fire upon submission to add the data and rerender the list, and a model to control the data. We'll get to these in the next article.

* Previous
* Overview: Client-side JavaScript frameworks
* Next


Ember Interactivity: Footer functionality, conditional rendering - Learn web development

Ember Interactivity: Footer functionality, conditional rendering
================================================================

* Previous
* Overview: Client-side JavaScript frameworks
* Next

Now it's time to start tackling the footer functionality in our app. Here we'll get the todo counter to update to show the correct number of todos still to complete, and correctly apply styling to completed todos (i.e. where the checkbox has been checked). We'll also wire up our "Clear completed" button. Along the way, we'll learn about using conditional rendering in our templates.

|  |  |
| --- | --- |
| Prerequisites: |
 At minimum, it is recommended that you are familiar with the core
 HTML,
 CSS, and
 JavaScript languages, and
 have knowledge of the
 terminal/command line.

 A deeper understanding of modern JavaScript features (such as classes,
 modules, etc.), will be extremely beneficial, as Ember makes heavy use
 of them.
  |
| Objective: |
 To continue our learning about components classes, start looking at
 conditional rendering, and wire up some of our footer functionality.
  |

Connecting the behavior in the footer
-------------------------------------

To get the footer working, we need to implement the following three areas of functionality:

* A pending todo counter.
* Filters for all, active, and completed todos.
* A button to clear the completed todos.

1. Because we need access to our service from the footer component, we need to generate a class for the footer. Enter the following terminal command to do so:

```bash
ember generate component-class footer
```

2. Next, go and find the newly-created `todomvc/app/components/footer.js` file and update it to the following:

```js
import Component from "@glimmer/component";
import { inject as service } from "@ember/service";

export default class FooterComponent extends Component {
  @service("todo-data") todos;
}
```

3. Now we need to go back to our `todo-data.js` file and add some functionality that will allow us to return the number of incomplete todos (useful for showing how many are left), and clear the completed todos out of the list (which is what the "Clear completed" functionality needs).
 In `todo-data.js`, add the following getter underneath the existing `all()` getter to define what the incomplete todos actually are:

```js
get incomplete() {
  return this.todos.filterBy('isCompleted', false);
}
```

Using Ember's `ArrayProxy.filterBy()` method, we're able to easily filter Objects in our array based on simple equals conditions. Here we're asking for all the todo items where the `isCompleted` property is equal to `false`, and because `isCompleted` is `@tracked` in our `Todo` object, this getter will re-compute when the value changes on an Object in the array.
4. Next, add the following action underneath the existing `add(text)` action:

```js
@action
clearCompleted() {
  this.todos = this.incomplete;
}
```

This is rather nice for clearing the todos — we just need to set the `todos` array to equal the list of incomplete todos.
5. Finally, we need to make use of this new functionality in our `footer.hbs` template. Go to this file now.
6. First of all, replace this line:

```hbs
<strong>0</strong> todos left
```

With this, which populates the incomplete number with the length of the `incomplete` array:

```hbs
<strong>{{this.todos.incomplete.length}}</strong> todos left
```

7. Next, replace this:

```hbs
<button type="button" class="clear-completed">
```

With this:

```hbs
<button type="button" class="clear-completed" {{on 'click' this.todos.clearCompleted}}>
```

 So now when the button is clicked, the `clearCompleted()` action we added earlier is run.
 However, if you try to click the "Clear Completed" button now, it won't appear to do anything, because there is currently no way to "complete" a todo. We need to wire up the `todo.hbs` template to the service, so that checking the relevant checkbox changes the state of each todo. We'll do that next.

The todo/todos plural problem
-----------------------------

The above is fine, but we have another small issue to contend with. The "todos left" indicator always says "x todos left", even when there is only one todo left, which is bad grammar!

To fix this, we need to update this part of the template to include some conditional rendering. In Ember, you can conditionally render parts of the template using conditional content; a simple block example looks something like this:

```hbs
{{#if this.thingIsTrue}} Content for the block form of "if"
{{/if}}
```

So let's try replacing this part of `footer.hbs`:

```hbs
<strong>{{this.todos.incomplete.length}}</strong> todos left
```

with the following:

```hbs
<strong>{{this.todos.incomplete.length}}</strong>
{{#if this.todos.incomplete.length === 1}} todo
{{else}} todos
{{/if}} left
```

This will give us an error, however — in Ember, these simple if statements can currently only test for a truthy/falsy value, not a more complex expression such as a comparison. To fix this, we'll have to add a getter to `todo-data.js` to return the result of `this.incomplete.length === 1`, and then call that in our template.

Add the following new getter to `todo-data.js`, just below the existing getters. Note that here we need `this.incomplete.length`, not `this.todos.incomplete.length`, because we are doing this inside the service, where the `incomplete()` getter is available directly (in the template, the contents of the service has been made available as `todos` via the `@service('todo-data') todos;` line inside the footer class, hence it being `this.todos.incomplete.length` there).

```js
get todoCountIsOne() {
  return this.incomplete.length === 1;
}
```

Then go back over to `footer.hbs` and update the previous template section we edited to the following:

```hbs
<strong>{{this.todos.incomplete.length}}</strong>
{{#if this.todos.todoCountIsOne}}todo{{else}}todos{{/if}} left
```

Now save and test, and you'll see the correct pluralization used when you only have one todo item present!

Note that this is the block form of `if` in Ember; you could also use the inline form:

```hbs
{{if this.todos.todoCountIsOne "todo" "todos"}}
```

Completing todos
----------------

As with the other components, we need a class to access the service.

### Creating a todo class

1. Run the following command in your terminal:

```bash
ember generate component-class todo
```

2. Now go to the newly-created `todomvc/app/components/todo.js` file and update the contents to look like so, to give the todo component access to the service:

```js
import Component from "@glimmer/component";
import { inject as service } from "@ember/service";

export default class TodoComponent extends Component {
  @service("todo-data") todos;
}
```

3. Next, go back again to our `todo-data.js` service file and add the following action just below the previous ones, which will allow us to toggle a completion state for each todo:

```js
@action
toggleCompletion(todo) {
  todo.isCompleted = !todo.isCompleted;
}
```

### Updating the template to show completed state

Finally, we will edit the `todo.hbs` template such that the checkbox's value is now bound to the `isCompleted` property on the todo, and so that on change, the `toggleCompletion()` method on the todo service is invoked.

1. In `todo.hbs`, first find the following line:

```hbs
<li>
```

And replace it with this — you'll notice that here we're using some more conditional content to add the class value if appropriate:

```hbs
<li class={{ if @todo.isCompleted 'completed' }}>
```

2. Next, find the following line:

```hbs
<input
  aria-label="Toggle the completion of this todo"
  class="toggle"
  type="checkbox"
>
```

And replace it with this:

```hbs
<input
  class="toggle"
  type="checkbox"
  aria-label="Toggle the completion of this todo"
  checked={{ @todo.isCompleted }}
  {{ on 'change' (fn this.todos.toggleCompletion @todo) }}
>
```

**Note:** The above snippet uses a new Ember-specific keyword — `fn`. `fn` allows for partial application, which is similar to `bind`, but it never changes the invocation context; this is equivalent to using `bind` with a `null` first argument.

Try restarting the dev server and going to `localhost:4200` again, and you'll now see that we have a fully-operational "todos left" counter and Clear button:

![todos being marked as complete, and cleared](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_conditional_footer/todos-being-marked-completed-and-cleared.gif)

If you're asking yourself why we're not just doing the toggle on the component, since the function is entirely self-contained and not at all needing anything from the service, then you are 100% right to ask that question! However, because \*eventually\*, we'll want to persist or sync all changes to the todos list to local storage (see the final version of the app), it makes sense to have all persistent-state-changing operations be in the same place.

Summary
-------

That's enough for now. At this point, not only can we mark todos as complete, but we can clear them as well. Now the only thing left to wire up the footer are the three filtering links: "All", "Active", and "Completed". We'll do that in the next article, using Routing.

* Previous
* Overview: Client-side JavaScript frameworks
* Next