0
0
Svelteframework~30 mins

Named slots in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Named Slots in Svelte Components
šŸ“– Scenario: You are building a reusable card component for a website. The card should have separate areas for a header, main content, and footer. You want to use Svelte's named slots to allow flexible content insertion in these areas.
šŸŽÆ Goal: Create a Svelte Card component that uses named slots for header, content, and footer. Then use this component in an App.svelte file, filling each slot with different content.
šŸ“‹ What You'll Learn
Create a Card.svelte component with named slots: header, content, and footer.
Use the <slot name="..."> syntax inside the Card.svelte component.
In App.svelte, use the Card component and provide content for each named slot.
Ensure the default slot is not used; only named slots are used.
Use semantic HTML elements inside the card for accessibility.
šŸ’” Why This Matters
šŸŒ Real World
Named slots let you build flexible UI components where different parts can be filled with custom content. This is common in dashboards, cards, modals, and layout components.
šŸ’¼ Career
Understanding named slots is important for frontend developers working with Svelte or similar frameworks. It helps create reusable, accessible, and maintainable components.
Progress0 / 4 steps
1
Create the Card component with named slots
Create a Svelte component file named Card.svelte. Inside it, write HTML with three sections: a <header> containing a named slot called header, a <main> containing a named slot called content, and a <footer> containing a named slot called footer. Use the syntax <slot name="header"></slot> for each slot.
Svelte
Need a hint?

Use <slot name="header"></slot> inside <header> and similarly for content and footer.

2
Set up the App component to use Card
Create a file named App.svelte. Import the Card component using import Card from './Card.svelte';. Add the <Card> component in the markup. Do not add any slot content yet.
Svelte
Need a hint?

Use import Card from './Card.svelte'; and add <Card></Card> in the markup.

3
Add content to each named slot in App
Inside the <Card> component in App.svelte, add three elements with the slot attribute set to header, content, and footer respectively. For example, add a <h1 slot="header">Welcome</h1> for the header slot. Add a paragraph with slot="content" and a small footer text with slot="footer".
Svelte
Need a hint?

Use elements with slot="header", slot="content", and slot="footer" inside <Card>.

4
Add accessibility and semantic improvements
In Card.svelte, add aria-label="Card component" to the <main> element for accessibility. Also, add a class card to the outermost element (wrap the existing content in a <section class="card"> element).
Svelte
Need a hint?

Wrap content in <section class="card"> and add aria-label="Card component" to <main>.