0
0
Svelteframework~30 mins

svelte:component for dynamic components - Mini Project: Build & Apply

Choose your learning style9 modes available
Dynamic Component Rendering with <code>svelte:component</code>
📖 Scenario: You are building a simple Svelte app that shows different greeting messages depending on the user's mood. Each mood has its own small component that displays a unique message.
🎯 Goal: Build a Svelte app that uses svelte:component to dynamically render one of three greeting components based on a selected mood.
📋 What You'll Learn
Create three Svelte components named Happy.svelte, Sad.svelte, and Excited.svelte with distinct greeting messages.
Create a main App.svelte file that holds the current mood in a variable called currentMood.
Use a configuration variable components that maps mood names to their respective components.
Use svelte:component in App.svelte to render the component matching currentMood.
Add buttons to change currentMood dynamically.
💡 Why This Matters
🌍 Real World
Dynamic component rendering is useful in apps where the UI changes based on user choices or data, such as dashboards, forms, or multi-step wizards.
💼 Career
Understanding <code>svelte:component</code> helps you build flexible and maintainable Svelte apps that adapt to user input or external data, a common requirement in frontend development jobs.
Progress0 / 4 steps
1
Create the greeting components
Create three Svelte components named Happy.svelte, Sad.svelte, and Excited.svelte. Each component should export a default component that renders a <h2> with these exact texts respectively: "I am feeling happy!", "I am feeling sad.", and "I am feeling excited!".
Svelte
Hint

Each component is a simple Svelte file with an <h2> tag containing the exact text.

2
Set up the mood state and components map in App.svelte
In App.svelte, import the three components Happy, Sad, and Excited. Create a variable called currentMood and set it to the string "Happy". Then create a constant object called components that maps the strings "Happy", "Sad", and "Excited" to their respective imported components.
Svelte
Hint

Use import statements for each component. Then create currentMood as a string and components as an object mapping mood names to components.

3
Render the dynamic component using svelte:component
In App.svelte, use the <svelte:component> tag to render the component that matches the current mood. Use the this attribute with the value components[currentMood].
Svelte
Hint

Use <svelte:component this={components[currentMood]} /> to render the chosen component.

4
Add buttons to change the mood dynamically
Below the dynamic component in App.svelte, add three <button> elements labeled exactly Happy, Sad, and Excited. Each button should have an on:click event that sets currentMood to the respective mood string.
Svelte
Hint

Add three buttons with on:click handlers that update currentMood to the exact mood strings.