Домой United States dc3 United States software in english pdf How To Handle Forms in Svelte?

How To Handle Forms in Svelte?

293
0
ПОДЕЛИТЬСЯ

Forms are essential to any kind of web application development and in this post, we will learn how to handle them in Svelte by using on:submit directive.
Join the DZone community and get the full member experience. In this post, we will learn how to handle forms in Svelte. Forms are an integral part of any web application. They are the primary way in which you collect information from the application user. Forms can enhance the user experience. Also, they can have a significant impact on the overall data quality of your application. Let us now put together the form: This is a very basic form with just two fields. We have the bookName and the author_name. Also, we have a button to submit the form. However, currently, we don’t have any handler for the same. Let us create the form submit handler: We use the on:submit handler. The preventDefault is to prevent the form submission to trigger an HTTP request as per the default form behavior. Basically, we want to trigger the function submitForm. In the script section of our component, we can also add a placeholder function. Svelte supports two-way binding using which we can connect the form input fields with the component data fields. See the updated form HTML: As you can see, we use the bind:value directive to bind the input fields to the respective component data field. We also finish the implementation of the submitForm() function. Basically, we generate a new book record and insert the same into the books array. Please note the use of the below line: We don’t use normal array functions like push() here. This is because these functions do not trigger Svelte’s reactivity. This is explained in the detailed post about correctly updating arrays in Svelte. In a nutshell, we use the assignment operator to update the books array. Finally, we have to show the books that are added using the form. Below is the updated version of the component: We use the #each block to render the list of books. You can read more about it in this detailed post on Svelte Each Block. Below is the code for the Book component: It simply receives the bookName and the authorName and displays them. We can now run the app and if we use the form to add records, we will have them listed properly. With this, we have successfully learned how to handle forms in Svelte. We used the on:submit listener to trigger a function on form submission and then, update the bound input values as part of the books array. If you have any comments or queries about the post, please feel free to mention them in the comments section. Published at DZone with permission of Saurabh Dashora. See the original article here. Opinions expressed by DZone contributors are their own.