0
0
Svelteframework~15 mins

Default actions in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Default Actions in Svelte
📖 Scenario: You are building a simple interactive button in a Svelte app. You want to use a default action to automatically focus the button when it appears on the page.
🎯 Goal: Create a Svelte component with a button that uses a default action to focus itself when the component loads.
📋 What You'll Learn
Create a Svelte component with a <button> element
Define a default action called focusOnMount that focuses the button element
Apply the use:focusOnMount directive to the button
Ensure the button is focused automatically when the component renders
💡 Why This Matters
🌍 Real World
Default actions in Svelte help automate common tasks like focusing elements, adding event listeners, or setting styles when components appear.
💼 Career
Understanding default actions is useful for building interactive, accessible web apps efficiently with Svelte.
Progress0 / 4 steps
1
Create the button element
Create a Svelte component with a <button> element that has the text Click me.
Svelte
Hint

Use the <button> tag and put the text Click me inside it.

2
Define the default action to focus the button
Add a focusOnMount function that takes a node parameter and calls node.focus() immediately. Return an empty object from the function.
Svelte
Hint

The default action is a function that receives the element as node. Call node.focus() inside it.

3
Apply the default action to the button
Use the use:focusOnMount directive on the <button> element to apply the focus action.
Svelte
Hint

Add use:focusOnMount inside the opening <button> tag.

4
Complete the component with export
Ensure the focusOnMount function is exported so it can be used as a default action in the component.
Svelte
Hint

The function must be exported with the export keyword.