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 –
-
src
– Since image propertysrc
as well as local variablesrc
have same names so instead of writing<img src={src}>
we simplified it to<img {src}>
. Both notations are perfectly alright to use. -
name
–name
variable is used as text ofh3
tag as well as value ofalt
attribute inimg
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 –
-
on:click
– This is the way we add click events on elements. -
increaseCount
– It is the function which is getting called on the click of button. Note that we are not usingincreaseCount()
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()}