Given the following Svelte code using <svelte:component>, what will be displayed on the page?
<script> import Button from './Button.svelte'; import Link from './Link.svelte'; let current = Button; </script> <svelte:component this={current} text="Click me" />
Look at the value of current and which component it points to.
The this attribute in <svelte:component> dynamically renders the component assigned to current. Since current is Button, the Button component renders with the given text.
<svelte:component> to render a dynamic component?Choose the correct syntax to render a dynamic component stored in the variable componentVar with a prop title set to 'Hello'.
The this attribute expects a component reference, not a string or a different attribute name.
The correct syntax uses this={componentVar} to tell Svelte which component to render dynamically. Other options either use wrong attribute names or incorrect value types.
Consider this Svelte component that switches between two components dynamically on button click. What text is shown after clicking the button twice?
<script> import A from './A.svelte'; import B from './B.svelte'; let current = A; function toggle() { current = current === A ? B : A; } </script> <button on:click={toggle}>Switch</button> <svelte:component this={current} />
Think about how the toggle function changes current each click.
Starting with current = A, first click changes it to B, second click changes it back to A. So after two clicks, component A is shown.
Examine the code below. Why does it cause a runtime error when rendered?
<script> let componentName = 'MyComponent'; </script> <svelte:component this={componentName} />
Check the type of value passed to this in <svelte:component>.
The this attribute requires a component reference (an imported component or a variable holding a component), not a string with the component's name. Passing a string causes a runtime error.
<svelte:component> improve component reuse?Which statement best explains the benefit of using <svelte:component> for dynamic components?
Think about how dynamic rendering reduces repetitive code.
<svelte:component> lets you choose which component to render at runtime using a variable. This avoids writing many {#if} blocks and makes code cleaner and more reusable.