Skip to content

Instantly share code, notes, and snippets.

@matthew-ia
Last active March 29, 2022 13:47
Show Gist options
  • Save matthew-ia/08837ee4910090b4653805c501eac9d7 to your computer and use it in GitHub Desktop.
Save matthew-ia/08837ee4910090b4653805c501eac9d7 to your computer and use it in GitHub Desktop.
Render a Svelte component using a switch pattern
<script>
import A from './a.svelte';
import B from './b.svelte';
import C from './c.svelte';
// assuming `state` prop is managed externally and passed into this component
export let state;
function component(current) {
switch(current) {
case 'a':
return A;
case 'b':
return B;
case 'c':
return C;
default:
return A;
}
}
</script>
<!-- Render -->
<svelte:component this={component(state)} />
<!-- Alternative to using a true `switch`, by using and object (key-value pairs) -->
<script>
import A from './a.svelte';
import B from './b.svelte';
import C from './c.svelte';
// assuming `state` prop is managed externally and passed into this component
export let state = 'a';
const components = {
'a': A,
'b': B,
'c': C,
}
</script>
<!-- Render -->
<svelte:component this={components[state]} />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment