Creating Your First Component

By default, Svelte on Rails looks for components in app/frontend/components.

The Component File

Create a new file at app/frontend/components/UserGreeting.svelte:

<script>
  /* Svelte 5 Runes mode */
  let { name = "Guest", messageCount = 0 } = $props();
</script>

<div class="greeting-card">
  <h1>Hello, {name}!</h1>
  <p>You have {messageCount} new messages.</p>
</div>

<style>
  .greeting-card {
    padding: 1rem;
    border: 1px solid #ccc;
    border-radius: 8px;
  }
</style>

Note on Paths

The component name you will use in Rails view helpers is the path relative to app/frontend/components, excluding the .svelte extension. In this case: UserGreeting.

Integrating with Rails Views

To render your component, use the svelte helper in any Rails view (.html.erb).

Basic Usage

Pass the component name and a hash of props:

<%= svelte_component 'UserGreeting', name: @user.name, messageCount: 5 %>

How it Renders

  1. Server-Side: Rails generates a div wrapper with the class svelte-component. If SSR is enabled, the initial HTML is rendered inside this div.
  2. Client-Side: The @csedl/svelte-on-rails package “hydrates” the div, making it reactive.

Copyright © 2025-2027 sedlmair.ch. Distributed by MIT license.