Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Svelte Component as Props

I am pretty new to the svelte environment, I have some react code and try to convert them as svelte for the learning purpose.

In the react, we can pass a string or React Node as props.

<TabPane
name="profile"
title={<img src="images/profile.svg" alt="Profile" />}
key="1"
>
    {/** some code **/} 
</TabPane>

I am trying to use the same code in svelte, but it throws an error. enter image description here

like image 367
Naveen DA Avatar asked Nov 24 '25 12:11

Naveen DA


1 Answers

In many cases you'll want to use slots as Tan Li Hau suggested. However, it is possible to pass components as props. For this, we are going to make use of <svelte:component>. It's quite restrictive, but it's a possibility.

https://svelte.dev/docs#svelte_component

<svelte:component>

Normally, you'd use <svelte:component> like this:

<script>
  import Component from './component.svelte'
</script>

<svelte:component this={Component} foo={bar} />

The above is equivalent to this:

<script>
  import Component from './component.svelte'
</script>

<Component foo={bar} />

Passing down components through props

This means we can actually pass down components through props.

<!-- app.svelte -->

<script>
  import ComponentA from './component-a.svelte'
  import ComponentB from './component-b.svelte'
</script>

<ComponentA foo={ComponentB} />

And render the component…

<!-- component-a.svelte -->

<script>
  export let foo
</script>

<svelte:component this={foo} />

Caveats

Note there are a few things you can't do:

  • Set props on the component passed down through props
  • Pass down components which children through props
  • Or do pretty much anything else with the component passed down as a prop

Svelte may not even be designed to do this (even though it works). So yeah, unless you really need this, use slots. But now you know this is possible.

like image 59
Nick Avatar answered Nov 27 '25 00:11

Nick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!