In the previous article, we saw how we can use reactive declaration $ in Svelte. In this article, we’ll have a look at how we can automatically lowercase the user input using reactive declaration in Svelte.
Here’s the code we have for the example:
<script>
let name = 'Gautam';
$: lowercasedName = name.toLowerCase()
const setName = (event) => {
name = event.target.value
}
</script>
<div>
<p>Name in lower case: <span class="lc">{lowercasedName}</span></p>
<input type="text" value={name} on:input="{setName}"/>
</div>
Code language: HTML, XML (xml)
In the above code, we have a reactive state named name with initial value of Gautam.
We then have a reactive declaration named lowercasedName with a lowercased value of name. On line 14, we’re using a input field with initial value of name. It means that this input field will have ‘Gautam‘ pre-filled. This is only uni-direction up until now.
Then we have an event listener attached called on:input. We’ve bound this value to the method named setName. This method will set the value of name, received from the user input. This makes it bi-directional (or two-way data binding).
Here’s what the above code looks like in action: