Skip to content

Instantly share code, notes, and snippets.

@danmatthews
Created October 4, 2024 10:09
Show Gist options
  • Save danmatthews/eae31e79abdb012bd71548c785829f57 to your computer and use it in GitHub Desktop.
Save danmatthews/eae31e79abdb012bd71548c785829f57 to your computer and use it in GitHub Desktop.

Composition over configuration.

Some of our components, currently, expect an array or object of items passed in to render them, for example, a <Tab> component might expect:

<Tabs items={[
	{
		title: "Page 1",
		url: "/page-1",
		icon: "<svg></svg>",
	},
	{
		title: "Page 2",
		url: "/page-2",
		icon: "<img></img>",
	}
]} />

The problem with this is: from the parent component, you can’t SEE what is happening within the component, or customise individual items without having to pass ‘special’ configuration keys:

{
	title: "Page 1"
	url: "page-1",
	icon: "<svg></svg>",
	visible: $page.props.auth.super_admin, // only show for super admins
	extraMarginLeft: true, // your other items might not need this one
}

Imagine the same thing, but with composition:

<Tabs>
	{#if $page.props.auth.super_admin}
		<TabItem class="ml-4" url="/page-1">
			<svg></svg>
			Page 1
		</TabItem>
	{/if}

	<TabItem url="/page-2">Page 2</TabItem>
</Tabs>

You can:

  1. Control visibility using the usual flow-control.
  2. Specify classes on individual items to implement layout changes without needing to add items + config to the component.
  3. Allow passing different pieces of content like icons without needing to pass them awkwardly as strings.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment