I've been using on:click
and looking for an event using Svelte. How do I trigger a custom event within a child component that I can capture in a parent component? I've seen a tutorial where I can pass in something like this, however, I couldn't get it to hook up.
<Component on:customClick={myThing}>
The child component has some logic that looks like this:
<script>
export let myThing = '';
<script>
<input type="text" onClick={() => myThing= 'Update'} />
This does not seem to work, what am I missing?
You could dispatch event from children component and handle it in parent component
// children component
<script>
import { createEventDispatcher } from "svelte";
const dispatch = createEventDispatcher();
let count = 0;
function handleClick() {
count += 1;
dispatch("customClick", {
count
});
}
</script>
<button on:click={handleClick}>
Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
// parent component
<script>
import ChildrenComponent from "./ChildrenComponent.svelte";
let count;
const handleCustomClick = event => {
count = event.detail.count;
};
</script>
<main>
<p>Parent count: {count || 0}</p>
<ChildrenComponent on:customClick={handleCustomClick}/>
</main>
Below is the codesandbox demo
Reference:
Tutorials: Component events
Or like this (without dispatch):
Parent:
<script>
import Child from "./Child.svelte";
let count = 0;
const handleClick = () => {
count += 1;
};
</script>
<main>
<p>Parent count: {count}</p>
<Child {count} on:click={handleClick} />
</main>
Child:
// child component
<script>
export let count;
</script>
<button on:click>
Clicked {count}
</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With