sveltesvelte-3svelte-component

Currying Params, or, Component Factories in Svelte


I have a simple Svelte component <Greet /> which takes two params:

<script lang=ts>
  export let greeting: string;
  export let name: string;
</script>

<strong>{greeting}, {name}!</strong>

How do I create a function which takes a single parameter, name, and returns a new component which takes one param, greeting, and renders <Greet {greeting} {name} />? Like so:

<script lang=ts>
  import { greetFactory } from './greetFactory';

  const GreetMike = greetFactory('Mike');
</script>

<GreetMike greeting="Hello" />
// renders <Greet greeting="Hello" name="Mike" />
// which in turn renders <strong>Hello, Mike!</strong>

In other words: How do I curry a param of a component?


Solution

  • You can use the client-side component API to merge the props in. It would look something like this:

      function greetFactory(name) {
            return function({ props, ...rest }) {
                return new Greet({
                    props: {
                        name,
                        ...props,
                    },
                    ...rest
                });
            }
      }
    

    REPL

    (If name is applied before the other props, it can even be overridden in the HTML.)