Svelte: Using Javascript variables for displaying data / attributes in html

In this article we will learn an important concept which is the foundation for props in Svelte. Javascript variables are reactive in Svelte. It means that if you update the value of a variable, the change will be reflected in html.

Code Example

<script>
  let src = 'https://i.ytimg.com/vi/MAfIvBgChjQ/maxresdefault.jpg';
  let name = 'Dr. Banner';
</script>

<h3>{name} is Hulk</h3>
<img {src} alt="{name} is Hulk">

<style>
img{
  width: 100%;
  max-width: 400px;
}
</style>

Here are the few important points about this code –

  1. src – Since image property src as well as local variable src have same names so instead of writing <img src={src}> we simplified it to <img {src}>. Both notations are perfectly alright to use.
  2. namename variable is used as text of h3 tag as well as value of alt attribute in img tag. It signifies that variables can be successfully rendered inside quotes "..." in Svelte.

Svelte variables are reactive

As we said earlier, Svelte variables are reactive. It means any change in value will be reflected on UI.

Example –

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

<h3>Count = {count}</h3>
<button on:click={increaseCount}>Increase Count by 1</button>

When you run this code and click on button, the count will increase and will be immediately reflected in h3 tag. Few points about this code –

  1. on:click – This is the way we add click events on elements.
  2. increaseCount – It is the function which is getting called on the click of button. Note that we are not using increaseCount() in click event. We are only using without parenthesis, increaseCount. This ensures that the function should not run while rendering. The other way of assigning function is – on:click={() => increaseCount()}

    Tweet this to help others

Live Demo

Open Live Demo