Written by: Geoffrey Callaghan

How To Create A Contact Form In Svelte

How To Create A Contact Form In Svelte

To create a contact form in Svelte with FabForm.io, you can follow these steps:

1. **Create a Svelte Project:**
   If you don't have a Svelte project set up, you can use the following commands to create a new one:

   ```bash
   npx degit sveltejs/template svelte-fabform
   cd svelte-fabform
   npm install
   ```

2. **Create a Contact Form Component:**
   Create a new Svelte component for your contact form. For example, you can create a file named `ContactForm.svelte`:

   ```html
   <script>
     let name = '';
     let email = '';
     let message = '';

     async function handleSubmit() {
       const formData = {
         name,
         email,
         message,
       };

       try {
         const response = await fetch('https://fabform.io/f/YOUR_FORM_ID', {
           method: 'POST',
           headers: {
             'Content-Type': 'application/json',
           },
           body: JSON.stringify(formData),
         });

         if (response.ok) {
           alert('Form submitted successfully!');
           // Reset form fields after successful submission
           name = '';
           email = '';
           message = '';
         } else {
           alert('Form submission failed.');
         }
       } catch (error) {
         console.error('Error submitting form:', error);
         alert('An error occurred while submitting the form.');
       }
     }
   </script>

   <style>
     /* Add your styling here */
   </style>

   <form on:submit|preventDefault={handleSubmit}>
     <label>
       Name:
       <input type="text" bind:value={name} />
     </label>

     <label>
       Email:
       <input type="email" bind:value={email} />
     </label>

     <label>
       Message:
       <textarea bind:value={message}></textarea>
     </label>

     <button type="submit">Submit</button>
   </form>
   ```

   In the code above, replace `YOUR_FORM_ID` with the actual form ID generated by FabForm.io when you create a form.

3. **Styling (Optional):**
   You can add styles to your form by modifying the `<style>` section in the `ContactForm.svelte` file.

4. **Use the Contact Form Component:**
   Import and use the `ContactForm` component in your `App.svelte` or any other component where you want to display the contact form:

   ```html
   <script>
     import ContactForm from './ContactForm.svelte';
   </script>

   <div>
     <h1>Contact Us</h1>
     <ContactForm />
   </div>
   ```

5. **Run your Svelte app:**
   Run your Svelte app using:

   ```bash
   npm run dev
   ```

   Open your browser and navigate to `http://localhost:5000` to see your contact form in action.

Remember to replace `'https://fabform.io/f/YOUR_FORM_ID'` with the actual URL generated by FabForm.io for your form.