Last active
March 29, 2022 13:47
-
-
Save matthew-ia/08837ee4910090b4653805c501eac9d7 to your computer and use it in GitHub Desktop.
Render a Svelte component using a switch pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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)} /> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- 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