Search code examples
sveltesveltekitsvelte-3svelte-component

How to pass a component as a prop in another component in svelte


I have 2 components - Slider Component and Button Component

Following is the Button component

<script>
  export button_type, custom_class, clickHander;
</script>


<button type={button_type} class= "{custom_class} on:click="{clickHandler}"
  <span>{buttonType.button_text}</span>
</button>

I am using the above Button component in Slider Component

<script>
import Button from './file_path'

</script>
<div>
   <h1>I am slider</h1>
   <Button />
</div>

My objective is to use this Slider component in the App.svelte (root) and pass the props to Button from App.svelte

How can I achieve this?


Solution

  • You could declare a property which is then spread on the Button.

    <script>
        import Button from './Button.svelte'
    
        export let buttonProps;
    </script>
    <div>
       <h1>I am slider</h1>
       <Button {...buttonProps} />
    </div>
    
    <!-- In App -->
    <Slider buttonProps={{ button_text: 'OK', clickHandler: () => alert('!') }} />
    

    REPL

    You can of course also declare individual properties and pass them on as needed.