Svelte 5 replaces framework-specific directives like on:click with standard HTML event properties (onclick, onkeydown, oninput). Custom component events are now passed as standard function props, eliminating complex event dispatchers.
Event Handlers & Prop Callbacks
React onClick props vs Svelte 5 onclick callback props.
1. Standard Native DOM Events
Events in Svelte 5 match native DOM element attributes directly:
<script lang="ts">
let count = $state(0);
function handleClick(event: MouseEvent) {
console.log('Clicked element at:', event.clientX, event.clientY);
count++;
}
</script>
<button onclick={handleClick}>
Clicked {count} times
</button>
<input oninput={(e) => console.log(e.currentTarget.value)} /> 2. Component Callbacks vs Event Dispatchers
To send events from a child component to a parent, declare a function property inside $props(). Callbacks act as typed, explicit event listeners:
Child Component (CustomButton.svelte):
<!-- CustomButton.svelte -->
<script lang="ts">
import type { Snippet } from 'svelte';
interface Props {
onclick?: () => void;
children: Snippet;
}
let { onclick, children }: Props = $props();
</script>
<button {onclick} class="btn">
{@render children()}
</button> Consuming the Custom Event in a Parent:
<!-- Parent.svelte -->
<script lang="ts">
import CustomButton from './CustomButton.svelte';
</script>
<CustomButton onclick={() => console.log('Button clicked in parent!')}>Save Changes</CustomButton> Key Core Advantages
- Native Web Standards: Uses familiar HTML attribute names (
onclick,onkeydown,onsubmit). - Type-Safe Payloads: Callback props accept typed parameters directly without event wrapping objects.
- Zero Boilerplate: Removes the need for component-level event dispatching tools.