Create a User Interface to Write Data
To write data to the database, we need a user interface. Let's create a user interface in this lesson.
Creating a user interface
Before we can write data to Firestore, we need some sort of input form. The Sapper template provides a blog (/blog
) by default, but its content is stored in a JavaScript file at services/web/src/routes/blog/_posts.js
. To demonstrate writing and reading data, we are going to provide a very basic form on the admin page where we can create a blog post and load a list of blog posts as it is currently displayed at /blog
.
We are not going to get fancy, and will just use the existing admin page to add the form. However, we do want to use a bit of abstraction to keep the code more maintainable. For that reason, we will create reusable UI components in the services/web/src/components/ui-elements/
directory.
Input group component
The first one is an
input-group.svelte
. Click Run and add the following code to the file:
<script>
export let elementType;
export let label;
export let id;
export let placeholder;
export let value;
</script>
<label for={id} class="mt-4 block text-sm font-medium leading-5 text-gray-700">
{label}
</label>
<div class="mt-1 relative rounded-md shadow-sm">
{#if elementType === "input"}
<input bind:value {id} {placeholder} class="block w-full" />
{:else if elementType === "textarea"}
<textarea bind:value rows="10" {placeholder} class="block w-full"></textarea>
{/if}
</div>
Click Run to save the changes.
It’s a bit of boilerplate code to create a <label>
element with a corresponding input, textarea, etc. field. The bind:value
directives and export let value;
tells Svelte to bind the value of <input>
or <textarea>
to the value prop we will use later.
Get hands-on with 1400+ tech skills courses.