Chapter 8: Bootstrap with Svelte

Integrating Bootstrap with Svelte is straightforward. This chapter covers installing Bootstrap, using Bootstrap components, and building responsive layouts in Svelte.

Installing Bootstrap

Bootstrap is already available via CDN in most Svelte projects. For better control, install it via npm:

npm install bootstrap

Then import it in your main.js:

import 'bootstrap/dist/css/bootstrap.min.css';

Using Bootstrap Components

Bootstrap components work seamlessly in Svelte. Here's an example with buttons and alerts:

<script>
  let showAlert = true;
</script>

{#if showAlert}
  <div class="alert alert-info" role="alert">
    This is a Bootstrap alert!
    <button type="button" class="btn-close" on:click={() => showAlert = false}></button>
  </div>
{/if}

<button class="btn btn-primary">Primary Button</button>
<button class="btn btn-success">Success Button</button>

Responsive Layouts

Use Bootstrap's grid system for responsive layouts:

<div class="container mt-5">
  <div class="row">
    <div class="col-md-6">
      <h2>Left Column</h2>
      <p>This content spans 6 columns on medium screens and up.</p>
    </div>
    <div class="col-md-6">
      <h2>Right Column</h2>
      <p>This is the right column content.</p>
    </div>
  </div>
</div>

Form Components

Bootstrap forms work great with Svelte's two-way binding:

<script>
  let formData = {
    email: '',
    password: ''
  };

  function handleSubmit() {
    console.log(formData);
  }
</script>

<form on:submit|preventDefault={handleSubmit}>
  <div class="mb-3">
    <label class="form-label" for="email">Email</label>
    <input type="email" class="form-control" id="email" bind:value={formData.email} />
  </div>
  <div class="mb-3">
    <label class="form-label" for="password">Password</label>
    <input type="password" class="form-control" id="password" bind:value={formData.password} />
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

Bootstrap and Svelte combine for powerful, responsive applications!