0
0
Svelteframework~30 mins

getContext in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Sharing Data Between Svelte Components Using getContext
📖 Scenario: You are building a simple Svelte app where a parent component shares a message with its child component without passing props directly.
🎯 Goal: Learn how to use setContext in a parent component and getContext in a child component to share data.
📋 What You'll Learn
Create a parent component that sets a context value
Create a child component that gets the context value
Display the shared message inside the child component
Use Svelte's setContext and getContext functions correctly
💡 Why This Matters
🌍 Real World
Sharing data between components without passing props directly is common in Svelte apps for cleaner and simpler code.
💼 Career
Understanding getContext and setContext helps in building scalable Svelte applications and working with component communication patterns used in professional projects.
Progress0 / 4 steps
1
Create the Parent Component with a Message
Create a Svelte component called Parent.svelte. Inside its <script> tag, declare a variable called message and set it to the string "Hello from Parent".
Svelte
Hint

Use let message = "Hello from Parent"; inside the <script> tag.

2
Set the Context in the Parent Component
In Parent.svelte, import setContext from "svelte". Then call setContext with the key "sharedMessage" and the value message.
Svelte
Hint

Remember to import setContext and call it with the key and message.

3
Create the Child Component to Get the Context
Create a new Svelte component called Child.svelte. Inside its <script> tag, import getContext from "svelte". Use getContext with the key "sharedMessage" to get the message and store it in a variable called receivedMessage.
Svelte
Hint

Use getContext("sharedMessage") and assign it to receivedMessage.

4
Display the Shared Message in the Child Component
In Child.svelte, below the paragraph, add a new paragraph that displays the variable receivedMessage using Svelte's curly braces syntax.
Svelte
Hint

Use {receivedMessage} inside a paragraph to show the message.