Using Svelte 5 and SvelteKit, I need to pass props to a child while this child is integrated to its parent using {@render children()}
.
I don't understand how I am supposed to pass props and get them in the child.
The following is not working but it illustrates what I want to do:
// Parent
{@render children({prop: value})}
// Child
let { prop } = $props()
Can someone tell me how to do this?
Using Svelte 5 and SvelteKit, I need to pass props to a child while this child is integrated to its parent using {@render children()}
.
I don't understand how I am supposed to pass props and get them in the child.
The following is not working but it illustrates what I want to do:
// Parent
{@render children({prop: value})}
// Child
let { prop } = $props()
Can someone tell me how to do this?
Share Improve this question edited Mar 11 at 14:26 jonrsharpe 122k30 gold badges268 silver badges476 bronze badges asked Mar 11 at 14:23 TheJofTheJof 1258 bronze badges 2 |2 Answers
Reset to default 2Layouts and pages in SvelteKit cannot pass properties like that.
Properties of components are separate from snippets arguments. You can only receive component properties from an instantiation of a component (<Component prop={...}>
). SvelteKit is doing the component instantiation and any properties passed in {@render children()}
will not be passed along to the component.
You can have some communication between layouts and child layouts/pages via contexts, though. This way you could also introduce custom slots as shown here, these could also receive arguments in the {#snippet}
definitions.
Since you mentioned that something needs to be reloaded in the parent:
If data is loaded via load
functions, you can cause these to reload via invalidate
/invalidateAll
.
You can pretty much do what you want with a small amendment.
e.g. the following displays Hello World.
You can have parameters on the children snippet and then pass those to a component if you need to.
You could also use the spread operator for cleaner code if you just want to forward to props on.
Playground
App.svelte
<script>
import Parent from "./Parent.svelte";
import Child from "./Child.svelte";
</script>
Hello
<Parent>
{#snippet children({ text })}
<Child {text} />
{/snippet}
</Parent>
Parent.svelte
<script>
let { children } = $props();
</script>
{@render children({ text: "World" })}
Child.svelte
<script>
let { text } = $props()
</script>
{text}
I did see your comment after writing most of my answer.
I need to find a way to reload the parent from the child.
I think that's what invalidate is for.
{@render children()}
is in a layout file indeed, but in my case the child is another layout file. I need to find a way to reload the parent from the child. – TheJof Commented Mar 11 at 14:33