Categories
JavaScript Svelte

Adding Reactivity to Our Svelte App

Svelte is an up and coming front end framework for developing front end web apps.

It’s simple to use and lets us create results fast.

In this article, we’ll look at how to run code reactivity when variable values change in a Svelte app.

Reactivity

We can add reactivity to our app with the $ sign. To do this, we write something like:

<script>  
  let count = 0;  
  $: doubleCount = count * 2; 
  const handleClick = () => {  
    count += 1;  
  };  
</script>

<main>  
  <button on:click={handleClick}>  
    Increment  
  </button>  
  <p>{count} {doubleCount}</p>  
</main>

Then code:

$: doubleCount = count * 2;

is reactive. This means that this will run with count is updated.

The $: is a label.

Therefore, when we click the button, both count and doubleCount will be updated with the latest values.

We can also put a block after the $: as follows:

<script>  
  let count = 0;  
  let doubleCount = 0;  
  $: {  
    doubleCount = count * 2;  
    console.log(count);  
  } 

  const handleClick = () => {  
    count += 1;  
  };  
</script>

<main>  
  <button on:click={handleClick}>  
    Increment  
  </button>  
  <p>{count} {doubleCount}</p>  
</main>

In the code above, we have the following:

$: {  
  doubleCount = count * 2;  
  console.log(count);  
}

We run code to update doubleCount and log count ‘s value in the same block.

Reactivity is triggered by assignment, so array methods like push and splice won’t automatically cause updates.

Therefore, we have to make the assignment event if the method changes the array in-place.

For instance, we can write the following code:

App.svelte :

<script>  
  let nums = [];  
  let count = 0; 
  const handleClick = () => {  
    nums = [...nums, count];  
    count++;  
  };  
</script>

<main>  
  <button on:click={handleClick}>  
    Add Number  
  </button>  
  <p>{nums.join(', ')}</p>  
</main>

In the code above, we have the handleClick function, which put the nums ‘s existing values in a new array with the spread operator, then we put the current count as the last element of the array instead of calling push to append count to the nums array.

Then we increment the count .

We should then get a list of numbers separated by commas as we click the Add Number button.

Assignment to properties of arrays and objects work the same way as an assignment to values themselves.

For instance, the following code:

App.svelte :

<script>  
  let nums = [];  
  let count = 0; 
  const handleClick = () => {  
    nums[nums.length] = count;  
    count++;  
  };  
</script>

<main>  
  <button on:click={handleClick}>  
    Add Number  
  </button>  
  <p>{nums.join(', ')}</p>  
</main>

works the same way as the code in the previous example.

The variable must appear on the left-hand side of the assignment operator for the assignment to be reactive.

Therefore, if we want to update a nested property, then we have to do something like the following:

App.svelte :

<script>  
  let obj = { foo: { bar: "bar" } }; const handleClick = () => {  
    obj.foo.bar = obj.foo.bar === "foo" ? "bar" : "foo";  
  };  
</script><main>  
  <button on:click={handleClick}>  
    Toggle  
  </button>  
  <p>{obj.foo.bar}</p>  
</main>

In the code above, if we click the Toggle button, we’ll assign the obj.foo.bar property to 'foo' or 'bar' depending on the value of obj.foo.bar .

Therefore, when we click the Toggle button, it should switch between foo and bar .

Conclusion

We can make a reactive property that’s derived from another property by writing: $: before the expression.

$: can also be used with a block.

To update a reactive value, we always have to reassign the value to the existing variable. As long as the variable we’re updating appears on the left side of the assignment expression, it’ll update.

Categories
JavaScript Svelte

Getting Started with Svelte Framework for Front End Development

Svelte is an up and coming front end framework for developing front end web apps.

It’s simple to use and lets us create results fast.

In this article, we’ll look at how to create our first app with Svelte.

Creating the Project

To write our first app, we can create our Svelte project by downloading thw svelte-app.zip from https://svelte.dev/blog/the-easiest-way-to-get-started.

Then we extract it and run npm install to install the packages.

Alternatively, we can run:

npx degit sveltejs/template my-svelte-project  
cd my-svelte-project  
npm install  
npm run dev

to create our Svelte project. We can substitute my-svelte-project with the name of our choice.

Then we go to http://localhost:5000/.

In index.js , we should have:

import App from "./App.svelte";const app = new App({  
  target: document.body  
});export default app;

as the entry point for our app.

It’ll display our app’s content in the body tag of our app.

Writing our First App

Now that we have our app running, we can start writing some code. For instance,

We can write the following:

App.svelte :

<script>  
  let name = "Jane";  
</script><main>  
  Hello {name}  
</main>

to create our first app. It has a name variable, which is set to 'Jane' , and we referenced it in our template.

Therefore, we should get Hello Jane displayed on the screen.

The code in the script tag is referenced in the main markup.

We can add styling to the style tag. For instance, we can write:

App.svelte :

<script>  
  let name = "Jane";  
</script><style>  
  p {  
    font-weight: bold;  
  }  
</style><main>  
  <p>Hello {name}</p>  
</main>

Then we make our text bold.

We can also call JavaScript inside the curly braces.

For instance, we can write:

App.svelte :

<script>  
  let name = "Jane";  
</script><main>  
  <p>Hello {name.toUpperCase()}</p>  
</main>

Then we see Hello JANE displayed on the screen.

Dynamic Attributes

We can add dynamic HTML attribute values to our app.

For instance, we can write the following to add an image with the URL set as a value of a variable:

App.svelte :

<script>  
  let src =  
    "https://images.unsplash.com/reserve/bOvf94dPRxWu0u3QsPjF\_tree.jpg?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=755&q=80";  
</script><main>  
  <img src={src} alt='' >  
</main>

In the code above, we set our image’s URL as the value of variable src .

Then we pass src as the value of src .

Shorthand

If we have something like src={src} , we can shrink it down to {src} .

We can rewrite the example above as follows:

<script>  
  let src =  
    "https://images.unsplash.com/reserve/bOvf94dPRxWu0u3QsPjF\_tree.jpg?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=755&q=80";  
</script><main>  
  <img {src} alt='' >  
</main>

Adding Components

We can add components to our app to divide our app’s code into smaller pieces.

To do that, we import the component and then referencing it in the markup as follows:

Button.svelte :

<script>  
</script><button>  
  Button  
</button>

App.svelte ;

<script>  
  import Button from "./Button.svelte";  
</script><main>  
  <Button />  
</main>

Then we get a button on the screen via the Button.svelte component.

Displaying Raw HTML

We can display Raw HTML in a component by writing the following code:

App.svelte :

<script>  
  let string = "<b>hello</b>";  
</script>

<main>  
  <p>{@html string}</p>  
</main>

The @html tag indicates that we want to display the content as raw HTML. Therefore, we’ll see a bold hello on the screen.

Handling Events

To make our app useful, it has to be able to handle user events.

For instance, we can use the on:click attribute to handle click events of a button as follows:

App.svelte :

<script>  
  let count = 0;  
  const handleClick = () => {  
    count += 1;  
  };  
</script>

<main>  
  <button on:click={handleClick}>  
    Increment  
  </button>  
  <p>{count}</p>  
</main>

In the code above, we have the on:click attribute set to the handleClick function we have in the script tag.

Then when we click the button, it’ll be called, count will be incremented. Then the latest value of count is displayed.

The DOM is automatically updated with the values in script are updated so we don’t have to worry about that.

We can also add variables that are derived from other ones in our code.

For instance, we can add a new variable that has the value which is double the count as follows:

<script>  
  let count = 0;  
  $: doubleCount = count * 2; 
  const handleClick = () => {  
    count += 1;  
  };  
</script>

<main>  
  <button on:click={handleClick}>  
    Increment  
  </button>  
  <p>{count} {doubleCount}</p>  
</main>

The code above has:

$: doubleCount = count * 2;

which is a variable computed from count . It tells Svelte to return the code whenever the referenced value change.

Conclusion

Getting started with Svelte is simple. It uses the same component-based architecture as other major frameworks like React, Angular, and Vue.

Each component has a logic part and a markup part. Events can be handled by setting event handlers on elements.

We can have variables that are derived from others by adding labels to them with the $ .