javascriptsveltesvelte-3

How can I receive arbitrary props in a Svelte component and pass to a child component?


I want to receive arbitrary props from "above" and spread them onto an <input>, as shown here where inputProps would become an object containing any additional props set on this component (similar to python's **kwargs, in case you're familiar):

<script>
export let id;
export ...inputProps;
</script>

<div>
    id: {id}
    <input {...inputProps} />
</div>

Can you point me toward the correct Svelte mechanism for accomplishing something like this? I have a feeling that I'm asking the wrong question, but I need a svelte developer to set me straight. Should I use a slot instead? Or learn about actions / "the use directive"?


Solution

  • Svelte now also offers $$restProps. See the Svelte API Docs - Attributes and props.

    $$props references all props that are passed to a component – including ones that are not declared with export. It is useful in rare cases, but not generally recommended, as it is difficult for Svelte to optimise.

    <Widget {...$$props}/>
    

    $$restProps contains only the props which are not declared with export. It can be used to pass down other unknown attributes to an element in a component.

    <input {...$$restProps}>