I want to create a ponent that will handle on:click
, but without exporting an handleClick
function; this is how it works right now
button.svelte
:
<script lang="ts">
export let handleClick: ((e: MouseEvent) => void ) | undefined = undefined
</script>
<button on:click={handleClick}>
<slot></slot>
</button>
app.svelte
:
<script lang="ts">
import Button from '$lib/button/button.svelte'
</script>
<Button handleClick={() => console.log('click!')}>
Click me!
</button>
How to change the Button element to use on:click
directly in the app ponent?
app.svelte
:
<Button on:click={handleClick}>
<slot></slot>
</Button>
I want to create a ponent that will handle on:click
, but without exporting an handleClick
function; this is how it works right now
button.svelte
:
<script lang="ts">
export let handleClick: ((e: MouseEvent) => void ) | undefined = undefined
</script>
<button on:click={handleClick}>
<slot></slot>
</button>
app.svelte
:
<script lang="ts">
import Button from '$lib/button/button.svelte'
</script>
<Button handleClick={() => console.log('click!')}>
Click me!
</button>
How to change the Button element to use on:click
directly in the app ponent?
app.svelte
:
<Button on:click={handleClick}>
<slot></slot>
</Button>
Share
Improve this question
asked Apr 10, 2023 at 9:01
UmerUmer
2013 silver badges8 bronze badges
1 Answer
Reset to default 10As per the Svelte documentation:
If the
on:
directive is used without a value, the ponent will forward the event, meaning that a consumer of the ponent can listen for it.
So you should be able to do this in button.svelte
:
<button on:click>
<slot></slot>
</button>
And then this should work in app.svelte
:
<script>
import Button from './button.svelte';
const handleClick = (event) => {
// …
};
</script>
<Button on:click={handleClick}>
Foo
</Button>